我有一个数据框,perc_responses_1,看起来像这样:
Options Percent
a_Option1 0.03
z_Option2 0.05
b_Option3 0.50
x_Option4 0.25
我想创建一个条形图,以降序值对条形进行排序。因此,第一个栏将是 b_Option3,第二个栏将是 x_Option4,依此类推。
我的实际行名很长,例如“购买更多土地用于公园和开放空间”,所以我想使用 str_wrap 来包裹标签。
这是行名称:
rownames(perc_responses_1) <- c("More bike paths and hiking trails","Removal of invasive plant species","Updating buildings and facilities","Purchasing more land for parks and open space")
但是,当我将 str_wrap 参数添加到 ggplot 函数中时,它会按字母顺序对列重新排序。如何同时使用字符串换行和按值重新排序列?
这是我的代码,当我运行此代码时,条形图按字母顺序排列:
ggplot(perc_responses_1, aes(x = reorder(Options, -Percent), Percent)) +
geom_bar(stat = "identity") +
coord_flip()+
scale_y_continuous(labels = scales::percent, limits = c(0, .7))+
aes(stringr::str_wrap(Options, 20), Percent) +
labs(x = "Options") + theme_bw()
当我运行此代码时,条形图的顺序正确,但标签未换行:
ggplot(perc_responses_1, aes(x = reorder(Options, -Percent), Percent)) +
geom_bar(stat = "identity") +
coord_flip()+
scale_y_continuous(labels = scales::percent, limits = c(0, .7))+
labs(x = "Options") + theme_bw()
您可以将
str_wrap
放入 scale_x_discrete
中,就像将 scales::percent
放入 scale_y_continuous
中一样。试试这个:
ggplot(perc_responses_1, aes(x = reorder(Options, -Percent), Percent)) +
geom_bar(stat = "identity") +
coord_flip() +
scale_y_continuous(labels = scales::percent, limits = c(0, .7)) +
scale_x_discrete(labels = \(x) stringr::str_wrap(x, 20)) +
labs(x = "Options") +
theme_bw()
我想补充一点,多年来,
coord_flip
一直是不必要的,您可以根据需要分配x
和y
,这样更清晰。 geom_col
是 geom_bar(stat = "identity")
的一个很好的快捷方式。我会对此进行修改:
ggplot(perc_responses_1, aes(y = reorder(Options, -Percent), Percent)) +
geom_col() +
scale_x_continuous(labels = scales::percent, limits = c(0, .7)) +
scale_y_discrete(labels = \(x) stringr::str_wrap(x, 20)) +
labs(y = "Options") +
theme_bw()