0

我有一个使用以下代码生成的条形图。

ggplot(data = df, aes(y = y_variable, fill = fact_variable)) + geom_bar(stat='count') + ggtitle("Graph")

这会生成以下图:(由于信息的敏感性,标题和轴已被裁剪) 在此处输入图像描述

然而,我希望情节按计数的降序排列。我怎么做?理想情况下,它应该看起来像这样,但在上图中使用了填充变量:

在此处输入图像描述

注意:y_variable 和 fact_variable 是因子变量。

stackoverflow 上的所有示例当前都将 reorder() 方法显示为解决方案,但这是针对在 x 轴上绘制 ax 变量的条形图。我有一个在 x 轴上有计数的条形图。

我如何在此基础上订购它?

4

2 回答 2

0

@Adishwar 如果您使用总计,通常建议使用 geom_col() 。这避免了您必须stat在 geom_bar() 中进行设置。

由于在数据方面没有可重复的示例,因此我已经大大简化了模拟变量名称的数据框。(您得到的错误是因为perc在您的情况下不知道,也就是“找不到对象”)。然后我使用 geom_col() 并为有序条形图重新排序。

您的示例未指定您从何处获得填充颜色。您可以根据需要手动设置它们。我使用开箱即用的颜色...

如果您不想显示标签,请将其设置为 NULL(将其删除)。

# setting up the test data with 2 categories and counts
df <- tribble(
  ~y_variable, ~fact_variable, ~count
  ,"Government" , "fact1"     , 100
  ,"Government" , "fact2"     , 200
  ,"Government" , "fact3"     , 500
  ,"Nonprofit"  , "fact1"     , 75
  ,"Nonprofit"  , "fact2"     , 200
  ,"Nonprofit"  , "fact3"     , 100
  ,"Other"      , "fact1"     , 300
  ,"Other"      , "fact2"     , 50
  ,"Other"      , "fact3"     , 80
)

# "standard barchart on counts (totals) using geom_col()
ggplot(data = df, aes(x = count, y = y_variable, fill = fact_variable)) + 
  geom_col() +

# this is to set the title, labels, etc ---------------------------
  labs(title = "your title here", fill = "possible fill title"
       ,x = "my counts or NULL", y = NULL) +
  theme_minimal()

对于有序版本,使用 reorder(variable, ordervariable)。确保分配正确的变量名称。

ggplot(data = df, aes(x = count, y = reorder(y_variable, count), fill = fact_variable)) + 
  geom_col() +
  labs(title = "your title here", fill = "possible fill title"
       ,x = "my counts or NULL", y = NULL) +
  theme_minimal()

在此处输入图像描述

于 2021-04-20T12:16:14.633 回答
0

试试这个

ggplot(df, aes(y = reorder(y_variable, -perc), fill  = fact_variable)) + geom_bar(stat='count') + ggtitle("Graph")
于 2021-04-20T06:13:28.140 回答