Wrong Order of Y Axis in Ggplot Barplot

Wrong order of y axis in ggplot barplot

You need to have numerical values in your value-column, currently you have factors:

library(reshape)
library(ggplot2)

data <- matrix(1:9, 3, 3)
colnames(data) <- c("approach", "best", "worst")
data[1,] <- c("a", 1.8, 157.0)
data[2,] <- c("b", 592.3, 1342.6)
data[3,] <- c("c", 613.1, 3744.1)
data <- as.data.frame(data)
data <- melt(data, id="approach")

data$value = as.double(levels(data$value))[data$value] # <-- converting

p <- ggplot(data, aes(x=approach, y=value, fill=variable)) +
geom_bar(position="dodge", stat="identity")
p

Sample Image

Wrong X axis order when using geom_bar() with character X object

You create x variable as factor and make sure the levels are properly ordered in it. In this example, you created a variable x which has the levels in proper order. If not, you have to assign a properly ordered vector to levels argument in x <- factor( x, levels = properly_ordered_vector ).

Also, make sure there is no duplicate values in the properly_ordered_vector, while assigning levels to a factor variable. Once you set it up like this, then ggplot will take care of order of xaxis labels based on the order of levels.

set.seed(1L)
y<-rnorm(10)
x<- c('0~0.1','0.1~0.2','0.2~0.3','0.3~0.4','0.4~0.5','0.5~0.6','0.6~0.7','0.7~0.8','0.8~0.9','0.9~1')
x <- factor( x, levels = x )
data<-data.frame(x,y)
library('ggplot2')
ggplot(data=data,aes(x=x,y=y))+geom_bar(stat="identity",fill='light blue')

Sample Image

How do I correct the scale and order of the y axis in R on a barplot

The question you were pointing to contains a very good idea, to use geom_rect instead. You could do something like the following (comments in code)

library(tidyverse)

# just some fake data, similar to yours
foo <- data.frame(id = "id", layer = letters[1:6], depth = c(5,10,12,15,20,25))

foo2 <-
foo %>%
# using lag to create ymin, which is needed for geom_rect
# transforming id into integers so i can add / subtract some x for xmin/xmax
mutate( ymin = lag(depth, default = 0),
id_int = as.integer(factor(id)))

# I am turning off the legend and labelling the layers directly instead
# using geom_text
# this creates a "wrong" y axis title which I'm changing with labs(y = ... )
# the continuous x axis needs to be turned into a fake discrete axis by
# semi-manually setting the breaks and labels
ggplot(foo2) +
geom_rect(aes(xmin = id_int - .5, xmax = id_int +.5,
ymin = ymin, ymax = depth,
fill = layer), show.legend = FALSE) +
geom_text(aes(x = id_int, y = (depth + ymin)/2, label = layer)) +
scale_x_continuous(breaks = foo2$id_int, labels = foo2$id) +
labs(y = "depth")

Sample Image

Created on 2021-10-19 by the reprex package (v2.0.1)

ggplot2: incorrect values on y-axis when using bar plot and stat = 'identity'

stat = "identity" means use the numbers exactly as they are - not "add them up".

In a simpler plot stat = "identity" numbers are added up by the default position = "stack", but it is the stacking that effectively adds the observations. When you override the default with position = "dodge", the bars are no longer stacked so no addition takes place.

Summarizing the data as you do with dplyr is a good way to achieve your goal. Another option is geom_bar(stat = "summary", position = "dodge", fun = sum) (thanks to @teunbrand in comments).

(If you stick with stat = "identity" you may want to switch to geom_col, which is the same as geom_bar but with stat = "identity" as the default.)

Order Bars in ggplot2 bar graph

The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.

## set the levels in order we want
theTable <- within(theTable,
Position <- factor(Position,
levels=names(sort(table(Position),
decreasing=TRUE))))
## plot
ggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)

barplot figure

In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. You can also specify the level order within the call to factor as above, and other ways are possible as well.

theTable$Position <- factor(theTable$Position, levels = c(...))

1 bar in wrong order in stacked bar chart (R ggplot2)

Using the following code, I get consistent order of the bars.

ggplot(data.location,aes(Location,value,fill=variable,order=variable))+
geom_bar(stat="identity")

Sample Image

Rearranging order of X axis causes errorbars to no longer match up on y axis

You need to pull the values of the error bars from the dataset with the re-ordered factor levels, rather than the original Kale_Nutrients data frame. This would change your code for the error bars to something like:

geom_errorbar(aes(ymin=P-P.s.e , ymax=P+P.s.e))+

Avoid ggplot sorting the x-axis while plotting geom_bar()

You need to tell ggplot that you've got an ordered factor already, so it doesn't automatically order it for you.

dat <- read.table(text=
"SC_LTSL_BM 16.8275
SC_STSL_BM 17.3914
proB_FrBC_FL 122.1580
preB_FrD_FL 18.5051
B_Fo_Sp 14.4693
B_GC_Sp 15.4986", header = FALSE, stringsAsFactors = FALSE)

# make V1 an ordered factor
dat$V1 <- factor(dat$V1, levels = dat$V1)

# plot
library(ggplot2)
ggplot(dat,aes(x=V1,y=V2))+geom_bar(stat="identity")

Sample Image

ggplotly with geom_bar shows wrong y-axis values when moving the cursor onto the bar

The value must be converted to a factor I think! Then it should work fine.

Libraries and the data:

require(data.table)
require(plotly)
require(ggplot2)

df1 <- data.frame(Time = seq(50, 290, 30), Enter = c(155000, 400000, 950000, 950000, 1000000, 1100000, 1100000, 1100000, 1150000),
Exit = c(150000, 165000, 167000, 225000, 500000, 560000, 562000, 564000, 590000))

Solution 1: Use value in a factor format:

   df1 <- melt(df1[,c('Time','Enter','Exit')],id.vars = 1)
df1$Time <- factor(df1$Time)
#df1$value <- format(df1$value, format="f", big.mark=",", scientific = F, digits = 0)

# Create Barplot of In and outflows
ggplotly(tooltip = c("y", "x", "colour"), p =
ggplot(df1, aes(x = Time, y = value)) +
geom_bar(aes(fill = variable), stat = 'identity', position = 'dodge', colour = 'black') +
scale_fill_manual(name = "", labels = c('Enter', 'Exit'), values= c('chartreuse4', 'brown')) +
labs(x = 'Time', y ='Value'))

Solution 2: to keep value with a numeric format but still the right tooltip separated by comma use the below version:

df1 <- melt(df1[,c('Time','Enter','Exit')],id.vars = 1)
df1$Time <- factor(df1$Time)
df1$value <- format(df1$value, format="f", big.mark=",", scientific = F, digits = 0)

# Create Barplot of In and outflows
p=ggplot(df1, aes(x = Time, y = value, text = paste0("Value:", value)) ) +
geom_bar(aes(fill = variable), stat = 'identity', position = 'dodge', colour = 'black') +
scale_fill_manual(name = "", labels = c('Enter', 'Exit'), values= c('chartreuse4', 'brown')) +
labs(x = 'Time', y ='Value')

ggplotly(p, tooltip = c("x","text"))


Related Topics



Leave a reply



Submit