如何用R的ggplot绘制目标组合图?双折线无法正常显示求解
解决方案
首先需要对数据进行预处理,将带百分比符号的字符转换为数值,同时在折线图中按member_casual分组,才能画出两条折线。以下是完整可运行的代码:
# 加载必要包 library(ggplot2) library(dplyr) # 你的数据集 yearly_percentage <- 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)) # 数据预处理:去除%并转为数值 yearly_percentage <- yearly_percentage %>% mutate( count_percentage = as.numeric(sub("%", "", count_percentage)), ride_Length = as.numeric(sub("%", "", ride_Length)), year = factor(year) # 将年份转为因子,保证x轴顺序正确 ) # 绘制组合图 ggplot(yearly_percentage, aes(x = year)) + # 分组柱状图 geom_bar(aes(y = count_percentage, fill = member_casual), position = "dodge", stat = "identity", alpha = 0.7) + # 两条折线:按member_casual分组,设置颜色区分 geom_line(aes(y = ride_Length, color = member_casual, group = member_casual), linewidth = 1.2) + # 添加折线的点标记 geom_point(aes(y = ride_Length, color = member_casual), size = 3) + # 设置坐标轴标签和标题 labs( x = "年份", y = "百分比", fill = "用户类型", color = "用户类型", title = "年度用户占比与骑行时长占比组合图" ) + # 调整主题样式 theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
问题分析
- 数据类型错误:原数据中的
count_percentage和ride_Length是带%的字符型,ggplot无法正确识别为数值进行绘图,必须转换为数值型。 - 折线图未分组:原代码的
geom_line没有指定group = member_casual,ggplot无法区分不同用户类型的数据点,因此只能画出一条混乱的线,而不是两条分别对应casual和member的折线。 - 年份轴顺序:将年份转为因子可以保证x轴按时间顺序排列,避免字符型年份排序混乱。
内容的提问来源于stack exchange,提问作者El Joven
相关产品推荐
相关产品推荐

