How to Force Specific Order of the Variables on the X Axis

How to force order on X-axis values with Seaborn?

Yes, give your x variable a Categorical dtype with all categories you want to appear in the order that you desire.

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

Changing the order of values on the x-axis in R

if you are willing to give ggplot2 a try

# data
anxiety <- c(1, 1, 2, 2, 3.5, 4, 4.5, 5, 5)
time <- c(10, 11, 12, 1, 2, 3, 4, 5, 6)
df <- data.frame(anxiety, time)
# order the level of time
df$time <- factor(df$time, order=TRUE, levels=time)

# plot
ggplot(df, aes(x=time, y=anxiety, group=1)) + geom_line()

Sample Image

how to correctly sort labels on axis?

You can just factor and change the levels of the Index column before the plot

PctCtr$Index <- factor(PctCtr$Index, levels=unique(PctCtr[,"Index"]))

How to change the order of values in a plot

You could use forcats::lvls_reorder(), like this:

Actigraph %>%
pivot_longer(cols = Standing:Sitting) %>%
ggplot(aes(x = name, y = value, fill = forcats::lvls_reorder(Condition, c(4,1:3)))) +
geom_boxplot() + labs(fill="Condition")


Related Topics



Leave a reply



Submit