Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 204742

How to combine line and bar chart for specific variable using R

$
0
0

I have a quite straightforward question. I would line to have a bar chart for var1, var2, var3 and var4 and a line chart for var5. Line and bars should be in the same chart. How can I get it keeping the long format with ggplot?

set.seed(1984)
start_date <- as.Date('2015-01-01')  
end_date <- as.Date('2017-01-01')  

date_yq <- as.Date(sample( as.numeric(start_date): as.numeric(end_date), 50, 
                           replace = T), 
                   origin = '1970-01-01')
var1 <- runif(50)
var2 <- runif(50)
var3 <- runif(50)
var4 <- runif(50)
var5 <- var1+var2+var3+var4

country <- c("AT","AT","AT","BE","BE","CY","CY","CY","DE","DE")
country_r <- rep(country, times = 5)
df <- data.frame(date_yq, country_r, var1, var2,var3,var4,var5)
View(df)

df_m <- gather(df, key="variable", value="value", c("var1","var2","var3","var4","var5"))


ggplot(df_m, aes(x=date_yq, y=value, colour=variable)) +
  geom_line()+
  geom_bar(stat = "identity")+
  xlab("Date") + 
  ylab("Value")

Edit: after some adjustments this is the code to reproduce the data:

 ggplot(data = df_m, aes(x = date_yq, y = value,fill=as.factor(variable))) +
  geom_bar(data = filter(df_m, variable != "var5"), stat = "identity", 
colour="black") + scale_fill_hue(c=45, l=80) +
  geom_line(data = filter(df_m, variable == "var5"), aes(col = variable, 
group = variable), colour="darkblue",size=1.3)

The problem is that the legend shows var5 as bar and not as a separate line. What could be the issue?


Viewing all articles
Browse latest Browse all 204742

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>