我有这个数据框:
df <- structure(list(variable = c("var1", "var1", "var1", "var1", "var2",
"var2", "var2", "var2", "var3", "var3", "var3", "var3", "var1",
"var1", "var1", "var1", "var2", "var2", "var2", "var2", "var3",
"var3", "var3"), percentage = c(12.565445026178, 18.848167539267,
42.4083769633508, 26.1780104712042, 3.57142857142857, 11.2244897959184,
45.9183673469388, 39.2857142857143, 4.59183673469388, 10.2040816326531,
57.1428571428571, 28.0612244897959, 3.03030303030303, 12.1212121212121,
39.3939393939394, 45.4545454545455, 2.94117647058824, 5.88235294117647,
38.2352941176471, 52.9411764705882, 17.6470588235294, 29.4117647058824,
52.9411764705882), score = structure(c(1L, 2L, 3L, 4L, 1L, 2L,
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 2L, 3L,
4L), .Label = c("1", "2", "3", "4"), class = "factor"), group = c("group1",
"group1", "group1", "group1", "group1", "group1", "group1", "group1",
"group1", "group1", "group1", "group1", "group2", "group2", "group2",
"group2", "group2", "group2", "group2", "group2", "group2", "group2",
"group2"), label = c(6.282722513089, 21.9895287958115, 52.6178010471204,
86.9109947643979, 1.78571428571429, 9.18367346938776, 37.7551020408163,
80.3571428571429, 2.29591836734694, 9.69387755102041, 43.3673469387755,
85.969387755102, 1.51515151515152, 9.09090909090909, 34.8484848484848,
77.2727272727273, 1.47058823529412, 5.88235294117647, 27.9411764705882,
73.5294117647059, 8.82352941176471, 32.3529411764706, 73.5294117647059
), percentage2 = c("13%", "19%", "42%", "26%", "4%", "11%", "46%",
"39%", "5%", "10%", "57%", "28%", "3%", "12%", "39%", "45%",
"3%", "6%", "38%", "53%", "18%", "29%", "53%")), .Names = c("variable",
"percentage", "score", "group", "label", "percentage2"), row.names = c(NA,
-23L), class = "data.frame")
现在我尝试使用以下代码制作带刻面的堆积条形图:
ggplot(df, aes(x = variable, y = percentage, fill = score)) +
geom_bar(stat = 'identity')+
geom_text(aes(y=label,label=percentage2), color='grey25', size=2) +
facet_wrap(~ group,ncol=2)+
coord_flip()
如您所见,标签不在栏中的正确位置。我需要一个相反的条形顺序。我知道这听起来有点像一个重复的问题,比如here,但是当我尝试这个解决方案时,我得到了这个错误:
警告:忽略未知的美学:订单
有谁知道如何解决这个问题?
答案 0 :(得分:0)
要做的几点:
geom_bar(stat = 'identity')
现已替换为geom_col()
y
美学position
参数与position_stack(vjust = 0.5)
代码:
library(ggplot2)
ggplot(df, aes(x = variable, y = percentage, fill = score)) +
geom_col(position = 'stack')+
geom_text(aes(label = percentage2),
position = position_stack(vjust = .5),
color='grey25',
size=2) +
facet_wrap(~ group,ncol=2) +
coord_flip()