如何更改x轴限制ggplot2 r

时间:2016-06-23 17:54:30

标签: r ggplot2 bar-chart axis limits

我想使用ggplot条形图设置x轴的限制。整个情节都没问题,但是当我使用ylim(1,6)(这些是我需要的限制)时,条形消失了。

数据:

var.A <- as.numeric(c(1:13))
var.B <- c(4.351833, 2.938000, 4.726465, 3.747162, 3.720737, 4.297117, 4.304500, 4.061277, 4.595236, 4.105444, 3.701684, 3.523563, 4.170000)
df <- data.frame(var.A,var.B)

Ggplot代码:

    ggplot(df, aes(x=factor(var.A), y=var.B)) + 
  geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.4) +
  coord_flip()+
  xlab("") +
  ylab("") +
  scale_x_discrete(labels=c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd",
                            "eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii",
                            "jjjjjj","kkkkkkk","llllll","mmmmmmmm"))

当我添加:ylim(1,6) +时出现问题。

另一件事。每个栏的颜色设置为fill="#fff68f"。是否有任何解决方案可以改变一个条形的颜色,例如,第一个从顶部开始我想要不同,即#ee2c2c

1 个答案:

答案 0 :(得分:2)

由于您使用了coord_flip(),因此您可以使用scale_y_continuous(expand=c(0,0),limits=c(1,6),oob = rescale_none)设置x轴限制,并为每个条形设置颜色scale_fill_manual(values = c("#ee2c2c",...)

因此,如果您想手动设置条形颜色,首先需要创建名称向量并将其插入数据框中:

names <- c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd",
"eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii",
"jjjjjj","kkkkkkk","llllll","mmmmmmmm")

var.A <- as.numeric(c(1:13))
var.B <- c(4.351833, 2.938000, 4.726465, 3.747162, 3.720737, 4.297117, 4.304500, 4.061277, 4.595236, 4.105444, 3.701684, 3.523563, 4.170000)
df <- data.frame(var.A,var.B,names)

要在ggplot中命令变量名称和颜色,您需要将矢量的结构从字符更改为因子(以获得级别)。

var.names = factor(df$names,
                levels = c("aaaaaaa aaaaa","bbbbb bbb bbbb","cccc ccc","dddd dd ddddd", "eee e eeeee e ee","ffffffff","gggggggg","hhhhhhh","iiii", "jjjjjj","kkkkkkk","llllll","mmmmmmmm"), ordered=T)

所以你的代码看起来像是:

ggplot(df, aes(x=var.names, y=var.B, fill=as.factor(var.names))) + 
  geom_bar(position=position_dodge(), stat="identity", width = 0.4) +
  coord_flip()+
  scale_y_continuous(expand=c(0,0),limits=c(1,6),oob = rescale_none) +
  xlab("") +
  ylab("") +
  scale_fill_manual(values = c(c(rep("#fff68f",12)),"#ee2c2c"))

输出

enter image description here