@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()
