how to change x-axis limits ggplot2 r

前端 未结 1 1652
逝去的感伤
逝去的感伤 2021-01-29 10:10

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:

相关标签:
1条回答
  • 2021-01-29 10:34

    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","ffffdd dd ffffffffd",
    "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","ffffdd dd ffffffffd", "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

    0 讨论(0)
提交回复
热议问题