在条形图之间设置固定差距

时间:2014-07-21 16:16:57

标签: r ggplot2

我有这个代码用于绘制我的图形,但我需要在x轴上设置具有固定距离的断点。

我如何更改此代码?

data1 <- as.matrix(read.table('$INPUT_FILE1', header = T));
data1.experiment <- as.numeric(data1[,\"Experiment\"]);
data1.obs <- as.numeric(data1[,\"Mean\"]);
data1.method <- as.factor(data1[,\"Method\"]);
df <- data.frame(data1.experiment, data1.method, data1.obs);
orderlist = c("5", "10", "20", "40", "60", "80");
ggplot(df, aes(x = data1.experiment, y = data1.obs, fill = data1.method), ylim=c(0,   380))+geom_bar(stat='identity', position='dodge')+labs(x='$xlabel',y='$ylabel',   fill='')+scale_fill_manual(values = c('indianred3','skyblue'), labels = c('DTB-MAC',   'IEEE802.11P'))+scale_y_continuous(limits = c(0, 380))+theme_bw()+theme(      panel.grid.major = element_line(colour = 'grey'), panel.border = element_rect(colour =   'black'), axis.line = element_blank(), panel.background = element_blank(),   legend.direction='horizontal', legend.position = c(0, 1), legend.justification = c(0, 1),   legend.background = element_rect(colour = NA));

例如,如果我想绘制此数据集

Experiment Method Mean
5 IEEE802.11P 73.692058824
10 IEEE802.11P 36.846029412
20 IEEE802.11P 109.911111111
40 IEEE802.11P 238.427111111
60 IEEE802.11P 326.812469136
80 IEEE802.11P 372.041388889
5 DTB-MAC 7.470588235
10 DTB-MAC 27.014705882
20 DTB-MAC 84.032148148
40 DTB-MAC 177.680148148
60 DTB-MAC 244.599555556
80 DTB-MAC 286.52462963

我需要的结果是x轴,标题为5,10,20,40,60,80,但它们之间的差距相同。

1 个答案:

答案 0 :(得分:0)

您只需要将x值设置为一个因子。

这是您的数据

data1<-data.frame(
    Experiment = c(5, 10, 20, 40, 60, 80, 5, 
10, 20, 40, 60, 80), 
    Method = c("IEEE802.11P", "IEEE802.11P", "IEEE802.11P", 
    "IEEE802.11P", "IEEE802.11P", "IEEE802.11P", "DTB-MAC", 
    "DTB-MAC", "DTB-MAC", "DTB-MAC", "DTB-MAC", "DTB-MAC"), 
    Mean = c(73.692058824, 36.846029412, 109.911111111, 
    238.427111111, 326.812469136, 372.041388889, 7.470588235, 
    27.014705882, 84.032148148, 177.680148148, 244.599555556, 
    286.52462963)
)

以及如何绘制它

library(ggplot2)
ggplot(data1, aes(x = factor(Experiment), y = Mean, fill =factor(Method))) +
    ylim(c(0,380)) +
    geom_bar(stat='identity', position='dodge')+
    labs(x='$xlabel',y='$ylabel',   fill='')+
    scale_fill_manual(values = c('indianred3','skyblue'), labels = c('DTB-MAC',   'IEEE802.11P'))+
    scale_y_continuous(limits = c(0, 380))+
    theme_bw()+
    theme(
        panel.grid.major = element_line(colour = 'grey'),
        panel.border = element_rect(colour =   'black'), 
        axis.line = element_blank(), 
        panel.background = element_blank(),
        legend.direction='horizontal',
        legend.position = c(0, 1), legend.justification = c(0, 1),
        legend.background = element_rect(colour = NA));

获取

enter image description here