2

I have the following code and it is only producing a barplot without the line. How can I tweak this code to get the secondary line? enter image description here

library(ggplot2) p1 <- ggplot() p1 <- p1 + geom_bar(data=subset(df, Year==2006), aes(x=factor(State),y=Rate), stat = "identity") p1 <- p1 + xlab("State") + ylab("Rate") + theme(axis.text.x = element_text(angle = 60, hjust = 1)) p1 <- p1 + geom_line(data = subset(df, Year==2006), aes(x=factor(State),y=Total.Poverty/1000),colour = "blue") p1 <- p1 + scale_y_continuous(sec.axis = sec_axis(~.*1000, name = "Total Poverty")) print(p1)

I've looked at ggplot2 overlay of barplot and line plot and I still can't figure out why the plot isn't showing the line.

enter image description here

2 Answers 2

0

You should provide a minimal data set to reproduce your problem, so I cannot test my solution, but I assume it is because a line on a factor scale does not work, so you should use:

p1 <- p1 + geom_line(data = subset(df, Year == 2006), aes(x = State, y = Total.Poverty / 1000), colour = "blue") 

instead.

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

1 Comment

I tried that and no success. Let me show you what I have. Reattaching file in original thread. df<-read.csv('Shiny/Vax.csv') df[4:17] <- lapply(df[4:17], as.numeric) colnames(df)[colnames(df)=="variable"] <- "Year" df <- df[,-1]
0

Had to add group = 1 in the code

library(ggplot2) p1 <- ggplot() p1 <- p1 + geom_bar(data=subset(df, Year==2006), aes(x=factor(State),y=Rate), stat = "identity") p1 <- p1 + xlab("State") + ylab("Rate") + theme(axis.text.x = element_text(angle = 60, hjust = 1)) p1 <- p1 + geom_line(data = subset(df, Year==2006), aes(x=factor(State),y=Total.Poverty/1000),colour = "blue", group = 1) p1 <- p1 + scale_y_continuous(sec.axis = sec_axis(~.*1000, name = "Total Poverty")) print(p1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.