简体   繁体   中英

GGplot is adding geom_line item as a geom_bar item in legend

I'm making sediment profile grain size distribution graphs, with stacked bar charts representing sand, silt and clay and an added line showing the median value for each depth. The graph looks good, yet the legend of my final output is mixing up some of my items.

Here is a breakdown of my code:

GS_as = data.frame(Depth = c(10,30,50,70,90),
clay = c(0.99,0,0,2.86,3.62),
silt = c(55.48,81.48,53.26,79.5,70.71), 
sand = c(43.53,18.52,46.74,17.64,25.67))

long = melt(GS_as,id = "Depth")

df = data.frame(Depth = c(10,30,50,70,90),
value = c(34.8,24.84,48.9,12.7,19.73),
variable = c("median","median","median","median","median"))

ggplot(long,aes(x=Depth,y=value,fill=variable)) + 
geom_bar(stat="identity") + coord_flip() +
scale_y_continuous(position = "right") +
scale_x_continuous(breaks = seq(10,900,by = 20),trans='reverse') + 
scale_fill_grey() + 
geom_line(data=df, aes(x= Depth, y = value,group=variable,colour=variable)) +
geom_point(data=df,aes(x= Depth, y = value,group=variable,colour=variable))

The final output is giving me this graph 1

Now, how do I remove median from the legend grayscale of grain sizes, and how do i remove the points from each box in grayscale? The points should only be presented with the median as a separate variable. I've searched long to find a solution, but have not gotten anywhere. I'm guessing I got to my final graph by a strange unintuitive way.

Additionally, if its possible I would also like the median line and points to be black, remove the variables title and group all the items under 1 level.

I appreciate any help you can give.

To fix your first issue with the median showing up in the fill legend you could make fill a locale aes of geom_bar . For a black color you could set the color via scale_color_manual . The legend titles could be set or removed via labs and finally (and as far as I understand you) you could "group all the items under 1 level" via theme options by removing the spacing between the legends and almost all the margin around them.

library(ggplot2)

ggplot(long, aes(x = Depth, y = value)) +
  geom_bar(aes(fill = variable), stat = "identity") +
  coord_flip() +
  scale_y_continuous(position = "right") +
  scale_x_continuous(breaks = seq(10, 900, by = 20), trans = "reverse") +
  scale_fill_grey() +
  geom_line(data = df, aes(x = Depth, y = value, group = variable, colour = variable)) +
  geom_point(data = df, aes(x = Depth, y = value, group = variable, colour = variable)) +
  scale_color_manual(values = c("black")) +
  labs(fill = NULL, color = NULL) +
  theme(legend.spacing.y = unit(0, "pt"), legend.margin = margin(1, 0, 0, 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM