0

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: enter image description here

How to get rid of the unnecessary line? Thank you!

1
  • 1
    Have you tried specifying fill = pos in geom_col(aes(...)) instead of the global plot? Commented Jan 20, 2022 at 16:23

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.