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")
How to get rid of the unnecessary line? Thank you!
CodePudding user response:
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)

