我有以下数据:
benchmark <- data.frame(
num_element = c(10000, 40000, 70000, 100000, 130000),
a = c(4.4363, 70.913, 215.83, 440.84, 740.84),
b = c(5.6356, 26.254, 48.570, 71.882, 95.455),
c = c(5.6356, 26.254, 48.570, 71.882, 95.455))
我想要一个分组的条形图,其中同一a, b, c
的所有num_element
值都在一起。这是我的绘制方式:
library(ggplot2)
library(reshape2)
data.m <- melt(benchmark, id.vars='num_element')
ggplot(data.m, aes(num_element, value))+
geom_bar(aes(fill = variable),
width = 0.4,
position = position_dodge(width=0.5),
stat="identity")+
theme(legend.position="top",
legend.title = element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank())
但是图看起来像这样:
尝试:
我将num_element
转换为所有字符串:
num_element = c('10000', '40000', '70000', '100000', '130000')
得到了这个情节:
如何按升序排列x轴?有没有一种方法可以将num_element
转换为String?
答案 0 :(得分:2)
您可以将num_element
列设为一个因素:
ggplot(data.m, aes(factor(num_element, ordered = TRUE), value))+
geom_bar(aes(fill = variable),
width = 0.4,
position = position_dodge(width=0.5),
stat="identity")+
theme(legend.position="top",
legend.title = element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank()) +
scale_x_discrete(labels = c('10000', '40000', '70000', '100000', '130000'))
# scale_x_discrete to write out all digits