Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you put text on different lines in ggplot

Tags:

r

ggplot2

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?

like image 316
user1471980 Avatar asked Jan 21 '15 17:01

user1471980


People also ask

How to Add a line and text in ggplot?

The “\n” symbol can be inserted into the position within each component, to insert a line break. The mappings in the ggplot method can be assigned to the labels of the data frame in order to assign the corresponding text at the respective coordinates of the data frame.

How do I add text to ggplot2?

You can use the annotate() function to add text to plots in ggplot2. where: x, y: The (x, y) coordinates where the text should be placed. label: The text to display.

How do you annotate a graph in R?

If you want to annotate your plot or figure with labels, there are two basic options: text() will allow you to add labels to the plot region, and mtext() will allow you to add labels to the margins.


1 Answers

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

like image 151
fabians Avatar answered Oct 22 '22 11:10

fabians