简体   繁体   中英

ggplot2 Plot DataFrame as Bar and Line

I am trying to make a bar plot + line 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. But the problem is, that pos should be applied only for Difference . The Total needs to be plotted as a line, but when I do this, the second line appears. 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. 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)

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