Theme elements in ggplot2 figure

2019-08-10 05:30发布

问题:

I am trying to tweak a few thematic elements in a ggplot2 figure. My three questions/goals for this multi-layered figure are (code for data follows at end):

  1. Create a x-axis tick mark label for all eight year, i.e., 2004-2011. I do not want a 'xlab' though.
  2. Remove the two filled dots from the "Infected Stems" legend b/c these "geom_bars" should not have dots associated with them (???).
  3. Change the Legend Title for the lines/points legend to "SOD-dead Stems".

My code is probably redundant to many of you, so feel free to provide suggestions anywhere, such as having only a single legend. I am new to ggplot (like it) but have trouble with "scales" thus far....


MY CODE FOR FIGURE:

##### BUILD UP DATAFRAME:
quag.infect= c(31, 52, 58, 74, 76, 85, 99, 102)
quke.infect= c(10, 13, 17, 20, 23, 27, 28, 27)
qusp.hosts = (rep(c("QUAG", "QUKE"), each=8))
year = rep(2004:2011, 2)
quag.dead = c(NA, 4,  11, 19, 33, 38, 48, 49)
quke.dead = c(NA,  1,  1,  1,  2,  3,  7,  8)

my.df = data.frame(Species=qusp.hosts, Year=year, 
Inf.ct = c(quag.infect, quke.infect), Sod.Dead=c(quag.dead, quke.dead))

##### Establish grey colors for bars:
grays = c(QUAG="gray50", QUKE="gray66")

##### Make multi-layered graphic:
library(ggplot2)
plot_x = ggplot(my.df, aes(Year, Inf.ct, fill=Species)) +
  geom_bar(stat="identity", position="dodge") +
  ylab(expression("Number of stems (dbh">="1-cm)", sep="")) +
  xlab("") +          
  scale_fill_manual(values=grays, "Infected Stems", labels = c("Black Oak", "Coast Live           Oak")) +
  geom_line(aes(y=Sod.Dead, linetype=Species)) +
  geom_point(aes(y=Sod.Dead, shape=Species)) 
plot_x 

Thanks, Sarah

回答1:

You're not far off.

For point 1: In place of xlab, use scale_x_continuous, setting the breaks, and specifying an empty title.

For point 2: Move fill = Species out of the global aes function into an aes function for geom_bar.

For point 3: Change the legend title within scale_shape and scale_linetype functions, making sure the same title goes into both.

Making these changes to the code for ggplot:

plot_x = ggplot(my.df, aes(Year, Inf.ct)) +
  geom_bar(aes(fill=Species), stat="identity", position="dodge") +
  ylab(expression("Number of stems (dbh">="1-cm)", sep="")) +
  scale_x_continuous("", breaks = seq(2004, 2011, 1)) +
  scale_fill_manual(values=grays, "Infected Stems", labels = c("Black Oak", "Coast Live Oak")) +
  geom_line(aes(y=Sod.Dead, linetype=Species)) +
  geom_point(aes(y=Sod.Dead, shape=Species)) +
  scale_shape("SOD-dead Stems") +
  scale_linetype("SOD-dead Stems")
plot_x 

gives the following plot:



标签: r ggplot2 legend