无count列时在ggplot2中筛选Top10/Bottom10站点绘制分面子图
解决站点计数筛选与分图绘制问题
步骤1:统计站点总骑行量并筛选目标站点
先通过dplyr统计每个起始站点的总骑行次数,再提取计数最高和最低的10个站点名称:
library(dplyr) library(ggplot2) # 统计每个起始站点的总骑行次数 station_counts <- rides_stations %>% count(starting_station_name, name = "total_rides") # 提取计数最高的10个站点(with_ties=FALSE确保仅取10个,如需保留并列可删除该参数) top10_stations <- station_counts %>% slice_max(n = 10, order_by = total_rides, with_ties = FALSE) %>% pull(starting_station_name) # 提取计数最低的10个站点 bottom10_stations <- station_counts %>% slice_min(n = 10, order_by = total_rides, with_ties = FALSE) %>% pull(starting_station_name)
步骤2:过滤原数据并添加分组标识
从原数据中筛选出目标站点,并标记其所属分组:
filtered_data <- rides_stations %>% filter(starting_station_name %in% c(top10_stations, bottom10_stations)) %>% mutate(group = case_when( starting_station_name %in% top10_stations ~ "Top 10 骑行量站点", starting_station_name %in% bottom10_stations ~ "Bottom 10 骑行量站点" ))
步骤3:绘制分面子图
通过facet_wrap生成两个子图,同时调整x轴标签避免拥挤:
ggplot(filtered_data, aes(x = starting_station_name, fill = member_status)) + geom_bar(position = "dodge") + # 可选:让会员/非会员柱子并排显示,默认是堆叠 facet_wrap(~group, scales = "free_x") + # 两个子图使用独立x轴 theme(axis.text.x = element_text(angle = 45, hjust = 1)) + # 旋转x轴标签 labs(x = "起始站点", y = "骑行次数", fill = "会员状态")
可选:分开绘制两个独立图表
如果不需要分面,可单独生成两个图表后拼接:
# 绘制Top10站点图表 top_plot <- ggplot(filtered_data %>% filter(group == "Top 10 骑行量站点"), aes(x = starting_station_name, fill = member_status)) + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + labs(title = "Top 10 骑行量起始站点", x = "站点名称", y = "骑行次数") # 绘制Bottom10站点图表 bottom_plot <- ggplot(filtered_data %>% filter(group == "Bottom 10 骑行量站点"), aes(x = starting_station_name, fill = member_status)) + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + labs(title = "Bottom 10 骑行量起始站点", x = "站点名称", y = "骑行次数") # 用gridExtra拼接两个图表(需先安装:install.packages("gridExtra")) library(gridExtra) grid.arrange(top_plot, bottom_plot, ncol = 1)
内容的提问来源于stack exchange,提问作者Xray25
相关产品推荐
相关产品推荐

