Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

control color in horizontal lines in ggplot2

Tags:

r

ggplot2

anybody could tell me what is going wrong with this script? I need 2 horizontal, black, dashed lines, but i got two red continuous instead. I am also unable to change the color of the plot margins to black, despite being using theme_bw, and also the fill of the boxplot is not grey,as required.

  dat1 <- data.frame (xvar = rep(c("A", "B"), each=10),

                yvar = 1:20 + rnorm(20,sd=3))

  ggplot(dat1, aes(x=xvar, y=yvar)) +
  theme_bw()+
  geom_boxplot(fill=grey)+
  geom_hline(aes(yintercept=40, color="black", linetype="dashed"))+
  geom_hline(aes(yintercept=33.84, color="black", linetype="dashed"))+  
  scale_x_discrete(name="") +
  scale_y_continuous(name="temperature (°C)")+
  opts(
    panel.grid.major = theme_line(size = 0.5, colour = NA),
    panel.background = theme_rect(colour = NA),   
    axis.title.y = theme_text(angle=90,face="bold", colour="black", size=14),
    axis.text.y  = theme_text(face="bold",angle=0, size=14,colour="black"),
    axis.title.x = theme_text(face="bold", colour="black", size=14),
    axis.text.x  = theme_text( size=14,vjust=1.2, colour=NA))

thanks a lot!

like image 625
Agus camacho Avatar asked Jul 02 '12 03:07

Agus camacho


People also ask

How do I specify colors in ggplot2?

When creating graphs with the ggplot2 R package, colors can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”). It is also possible to use pre-made color palettes available in different R packages, such as: viridis, RColorBrewer and ggsci packages.

How to create horizontal line in ggplot?

Example: To add the horizontal line on the plot, we simply add geom_hline() function to ggplot2() function and pass the yintercept, which basically has a location on the Y axis, where we actually want to create a vertical line.

How to add vertical lines in ggplot R?

To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.


1 Answers

Regarding the black dashed line, you should define it outside of the aes(). Try the code below:

geom_hline(aes(yintercept=40), color="black", linetype="dashed")

Regarding the box plot, you should correct your code to the one below:

geom_boxplot(fill="gray")

And finally, to get the black margin, note that you are setting the margin to have NA color in your opts(..., panel.background = theme_rect(colour = NA),...). To solve the issue try this:

panel.background = theme_rect(colour = "black")

Hope my comment helps.

like image 58
Sam Avatar answered Oct 11 '22 02:10

Sam