简体   繁体   English

ggplot2 Plot DataFrame 作为条和线

[英]ggplot2 Plot DataFrame as Bar and Line

I am trying to make a bar plot + line plot.我正在尝试制作一个酒吧 plot + 线 plot。 My data look like this:我的数据如下所示:

Year= c(1951, 1952, 1953, 1954, 1955, 1956)
Difference = c(-1, -2, 3, 1, -2, 1)
Total = c(-0.8, -0.7, 1.1, 2.3, 1.7, 1.6)
pos = c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE)

I use pos to separate negative and positive values to plot bars in different colors.我使用pos将负值和正值分隔为不同 colors 中的 plot 条。 But the problem is, that pos should be applied only for Difference .但问题是, pos应该只适用于Difference The Total needs to be plotted as a line, but when I do this, the second line appears. Total需要绘制为一条线,但是当我这样做时,会出现第二条线。 My code is:我的代码是:

ggplot(df, aes(x = Year, y = Difference, fill = pos)) +  geom_col(position = "identity", colour = "black", size = 0.25) +  scale_fill_manual(values = c("#CCEEFF", "#FFDDDD"), guide = "none")+ geom_line(mapping = aes(x=Year, y=Total),size=1,fill='grey',fatten = 1, guide = "none")

My result:我的结果: 在此处输入图像描述

How to get rid of the unnecessary line?如何摆脱不必要的线路? Thank you!谢谢!

You can move the fill aesthetic into the geom_col call.您可以将填充美学移动到 geom_col 调用中。 This should be what you are looking for这应该是您正在寻找的

library(ggplot2)

df <- data.frame(
  Year = c(1951, 1952, 1953, 1954, 1955, 1956),
  Difference = c(-1, -2, 3, 1, -2, 1),
  Total = c(-0.8, -0.7, 1.1, 2.3, 1.7, 1.6),
  pos = c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE)
)

ggplot(df, aes(x = Year, y = Difference)) +
  geom_col(aes(fill = pos), position = "identity", colour = "black", size = 0.25) +
  scale_fill_manual(values = c("#CCEEFF", "#FFDDDD"), guide = "none") +
  geom_line(aes(y = Total), size = 1)

Created on 2022-01-20 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2022 年 1 月 20 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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