how to change x-axis limits ggplot2 r -


i set limit x-axis using ggplot bar plot. whole plot ok, when use ylim(1,6) (these limits need) 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 add: ylim(1,6) + things going wrong.

and thing. color of every bar set fill="#fff68f". there solution change color of 1 bar, example first top i'd different, i.e. #ee2c2c.

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

so if set color of bars manually, first need create vector of names , insert in 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 order variable names , colors in ggplot need change structure of vector character factor (in order 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 code 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

enter image description here


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

delphi - Take screenshot in webcam using VFrames in Console Application -

php - Few issues in voting -