sov*_*014 -2 r legend bar-chart ggplot2
我的数据看起来像
language tone count tone_percent label_pos pos
1 c positive 3460 36.16977 18.08488 7
2 c neutral 2046 21.38825 46.86389 7
3 c negative 4060 42.44198 78.77901 7
4 c# positive 3732 41.26949 20.63475 3
5 c# neutral 1832 20.25876 51.39887 3
6 c# negative 3479 38.47175 80.76413 3
7 c++ positive 3136 33.13960 16.56980 8
8 c++ neutral 2008 21.21949 43.74934 8
9 c++ negative 4319 45.64092 77.17954 8
Run Code Online (Sandbox Code Playgroud)
我一直在尝试使用 ggplot2 条形图将它们可视化:
p <-ggplot() + theme_bw() + geom_bar(aes(y=tone_percent, x=reorder(language, -pos), fill=tone), data=data, stat="identity") +
geom_text(data=data, aes(x = language, y = label_pos, ymax=label_pos, hjust = 0.5, label = paste0(round(tone_percent),"%")), size=4) +
labs(x="Language", y="Percentage of tone") +
scale_fill_manual(values=c('#F45E5A', '#5086FF', '#17B12B')) +
theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank()) + coord_flip()
Run Code Online (Sandbox Code Playgroud)
但是,图例按字母顺序显示标签,但我想以与图表中绘制条形相同的顺序显示它们:正,然后中性,然后负
有什么办法可以实现这一点吗?
您可以传递函数guides的参数,这将反转图例顺序,而无需重新排序条形。清理了一下:scaleguide_legend(reverse = TRUE)
ggplot(data, aes(x = reorder(language, -pos), y = tone_percent, fill = tone)) +
geom_col() +
geom_text(aes(y = label_pos, label = paste0(round(tone_percent),"%"))) +
coord_flip() +
labs(x = "Language", y = "Percentage of tone") +
scale_fill_manual(NULL, values=c('#F45E5A', '#5086FF', '#17B12B'),
guide = guide_legend(reverse = TRUE)) +
theme_bw() +
theme(legend.position = "bottom",
legend.direction = "horizontal")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2565 次 |
| 最近记录: |