how to change x-axis limits ggplot2 r

2019-03-06 16:49发布

问题:

I would like to set limit for x-axis using ggplot bar plot. The whole plot is ok, but when I use ylim(1,6) (these are limits what I need) the bars disappear.

Data:

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 code:

    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"))

And when I add: ylim(1,6) + things are going wrong.

And another thing. The color of every bar is set as fill="#fff68f". Is there any solution to change color of one bar, for example the first from top I'd like to be different, i.e. #ee2c2c.

回答1:

Because you used coord_flip() you can set limits of x-axis with scale_y_continuous(expand=c(0,0),limits=c(1,6),oob = rescale_none) and for setting colors for every bar you can use scale_fill_manual(values = c("#ee2c2c",...).

So if you would like to set the color of bars manually, you first need to create vector of names and insert it in your dataframe:

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)

And to order variable names and colors in ggplot you need to change the structure of vector from character to factor (in order to get levels).

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)

So your code then looks like:

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"))

And output is