如何制作 geom_col

How to make a geom_col

我刚开始学习数据分析,我正在研究 google coursera 数据分析程序中的循环案例研究。我正在尝试制作 geom_col 但我做不到。

首先,我通过合并起点站名称和终点站名称创建了一个名为“路线”的新列 现在有两种类型的用户“临时”和“会员”。我想将休闲旅行和会员旅行共有的前 10 条路线中的 geom_col 并排显示,以便于比较。

所以我想要一个 geom_col,y 轴为路线,轴为会员和临时用户的旅行频率,将会员和临时用户并排放置以便于比较。

这是原始数据集的样本,仅包含相关列:

ride_id route member_casual
1       A        member   
2       A        casual  
3       B        member
4       C        casual
5       D        casual
There are 500 approx routes 

您可以使用 count() 函数计算每个 routemember_casual 组合的频率。添加 name= 参数可让您使用计数命名新列。 slice_max() 然后可以按我们称为 freq 的新频率列对行进行排序,然后是 select 前 n (10) 行。 slice_max() 的默认行为是保持平局,因此如果第 10 个 freq 值有平局,您可能会得到 10 个以上的结果。您可以将参数 with_ties = FALSE 添加到仅 return 前 10 行,忽略第 10 行中 freq 值可能具有的任何联系。然后绘制 routefreq 并告诉 ggplot 使用 member_casual 值填充条形颜色。将 position="dodge" 参数添加到 geom_col(默认为“stack”),以便 member_casual 条形图并排显示以便于比较。然后 coord_flip 将图形翻转为水平柱状图。

library(tidyverse)

dataframe |>  
  count(route, member_casual, name="freq") |> 
  slice_max(order_by = freq, n = 10) |> 
  ggplot(aes(route, freq, fill=member_casual)) +
  geom_col(position="dodge") +
  coord_flip() 

此外,如果您要为每种类型的会员寻找前 10 条路线(即休闲前 10 条路线和会员前 10 条路线,您可以在 [=16 之前添加 group_by(member_casual) =].

library(tidyverse)

dataframe |>  
  count(route, member_casual, name="freq") |> 
  group_by(member_casual) |>
  slice_max(order_by = freq, n = 10) |> 
  ggplot(aes(route, freq, fill=member_casual)) +
  geom_col(position="dodge") +
  coord_flip()