简体   繁体   中英

How to plot combo plot in R using ggplot

my data frame i am using is我正在使用的数据框

the output I'm trying to achieve 期望的输出 I achieved this output in excel and I'm trying to reproduce it in R but I am not able to get the 2 lines I tried using the code

ggplot(yearly_percentage) +
  geom_bar(aes(x=year, y=count_percentage, fill=member_casual), position = "dodge",stat = "identity") +
  geom_line( aes(x=year,y=ride_Length))

this is the output I get

here is my reproduceable sample of data frame

structure(list(year = c("2016", "2016", "2017", "2017", "2018", 
"2018", "2019", "2019", "2020", "2020"), member_casual = c("casual", 
"member", "casual", "member", "casual", "member", "casual", "member", 
"casual", "member"), count_percentage = c("23.88%", "76.12%", 
"21.86%", "78.14%", "18.79%", "81.21%", "23.06%", "76.94%", "11.31%", 
"88.69%"), ride_Length = c("45%", "55%", "42%", "58%", "46.6%", 
"53.4%", "51.5%", "48.5%", "42%", "58%")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -10L))

As the message suggest you have to set the group aes and as you probably want colored lines you have to map on the color aes additionally. Also note, that your columns are not numerics but characters. Hence you have to convert them to numerics and instead format as percentages via the labels argument of scale_y_continuous :

library(ggplot2)

yearly_percentage$count_percentage <- readr::parse_number(yearly_percentage$count_percentage)
yearly_percentage$ride_Length <- readr::parse_number(yearly_percentage$ride_Length)

ggplot(yearly_percentage) +
  geom_bar(aes(x = year, y = count_percentage, fill = member_casual), position = "dodge", stat = "identity") +
  geom_line(aes(x = year, y = ride_Length, color = member_casual, group = member_casual)) +
  scale_y_continuous(labels = scales::label_percent(scale = 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