13

My df looks like this:

 Product Day Month Total
Web Server, Applicatiion Server, Database Server, Middle Tier Tue 2015年01月01日 10
Web Server, Application Server, Database Server, Middle Tier Wed 2015年01月01日 6
Web Server, Application Server, Database Server, Middle Tier Wed 2015年02月01日 6

I need to create a heat map in ggplot2 where I need to insert Product name as geom_text.

I have this so far:

ggplot(cal, aes(x=Month, y=Day, fill=Total)) +
 geom_tile() +
 scale_fill_gradient2(high="red",mid="green",low="yellow", 
 na.value="white", midpoint=mean(cal$Total, na.rm=T))+scale_x_date(labels = date_format("%b-%Y"), breaks = date_breaks("month"))+
 geom_text(aes(label=Product))

What happens is since there are multiple Product names separated by comma, when I do geom_text (aes(label=Product)), text is written on top of each other.

Is it possible put each Product name on different lines?

asked Jan 21, 2015 at 17:21
2
  • 1
    ggplot2 can't do automatic linebreaks for you. Have you tried adding \n after , in your Product names? Commented Jan 21, 2015 at 17:26
  • @Roland, I just tried your recommendation inserting \n after the comma in my data frame, still the same. Text are written on top of each other. Commented Jan 21, 2015 at 17:31

1 Answer 1

33

Just add "\n" to your "Product" labels wherever you need a line break:

library(ggplot2)
df <- data.frame(
 label=c("bla \n foo", "first line \n second line"),
 x = c(1, 2), y =c(1,2))
ggplot(df, aes(x=x, y=y, label=label)) + geom_text()

enter image description here

answered Jan 21, 2015 at 17:31
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this, it seems to be working. But I still see text on top of each other. How else I can enforce each text to be on the new line?
position_dodge does not work with geom_text, so I guess you'll have to shorten your labels and/or reduce the fontsize (geom_text(size = 4) or sth like that) to avoid overlap.
Any way to control spacing between the two lines of text?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.