Order X Axis Day Values in Ggplot2

Order x axis day values in ggplot2

You need to reorder the levels of the day, which is what determines plotting order. You can either type out the days of the week, or use your favorite method for generating a sequence of Sunday to Saturday dates and call weekdays (or format or strftime with format = %A) on it. You can either do this on your data.frame before you plot (a good idea, as that's the best way to store the data anyway), or inside of aes when you plot:

ggplot(data = my_data, aes(x = factor(day, weekdays(min(my_data$date) + 0:6)), 
y = n,
col = week,
group = week)) +
geom_line() + geom_point() + xlab('Weekday')

plot with nicely ordered weekdays

Order Weekday by order in ggplot2/R

Just reorder factor levels:

  member_causal_weekly$weekday <- factor(member_causal_weekly$weekday,
levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))

chart <- ggplot(member_causal_weekly, aes(x=weekday, y=count, fill=weekday))+
geom_bar(stat="identity")+
facet_wrap(~member_casual)+
geom_text(aes(label=count), vjust=1.6, color="white", size=3)+
theme (axis.text.x=element_text(angle=45, hjust=1))

ggplot x axis order days

Make sample data with columns day and value.

df<-data.frame(day=c(30,31,1,2,3,4,5,6,7,8),value=rnorm(10))

If column day contains just day values as numbers you can convert them to factor and set levels as original order of values.

ggplot(df,aes(factor(day,levels=df$day),value,group=1))+geom_line()

How to order a ggplot x-axis by a variable containing a date range?

Generalizing to an arbitrary number of intervals is a bit more complicated, involving some functions from the stringr and lubridate packages. At least the way I got it to work was to:

  1. Extract the starting and ending year/month portions of the interval with stringr::str_sub() and converting them to dates with lubridate::dmy() after first adding an arbitrary day portion "01-" (just so lubridate can parse the string segments as dates)

  2. Use lubridate::interval() to define an interval from the now separate starting and ending date component columns

  3. Sorting the data based on the new interval column with dplyr::arrange()

  4. Converting the original EXTRACT column to a factor and defining the levels of the new factor version of the column using the unique() values of the EXTRACT column, which now appear in the order of ascending date intervals (due to step 3).

  5. Build the graph.

Code:

library(tidyverse)
library(lubridate)
df <- df %>%
mutate(EXTRACT_d1 = dmy(str_c("01-", str_sub(EXTRACT, end = 7))),#start date
EXTRACT_d2 = dmy(str_c("01-", str_sub(EXTRACT, start = 9))), #end date
EXTRACT_int = interval(EXTRACT_d1, EXTRACT_d2)) %>% #define interval
arrange(EXTRACT_int) #sort the data by the interval

df %>%
#now we convert the extract to a factor using the unique values after sorting
#based on the interval column
mutate(EXTRACT = factor(EXTRACT, levels = unique(so_df$EXTRACT))) %>%
ggplot(aes(x = EXTRACT, y = SIZE, group = GROUP)) +
geom_line(aes(color = GROUP), size = 2) +
expand_limits(x = 0, y = 0) +
xlab(expression("")) +
ylab(expression("Average monthly size")) +
scale_y_continuous(expand = c(0,0), labels = comma) +
theme(axis.text.y = element_text(size = 15),
axis.text.x = element_text(size = 15),
axis.title.y = element_text(size = 15),
axis.title.x = element_text(size = 15),
legend.position = "top",
legend.direction = "horizontal",
legend.title = element_blank(),
legend.spacing.x = unit(1.0, 'cm'),
legend.text = element_text(size = 15),
plot.background = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(), panel.grid.major.y = element_line(colour = "#E6E6E6"),
axis.line.y = element_blank(),
axis.ticks.y = element_blank()) +
coord_cartesian(clip = "off")

using factors to order ggplot x axis dates

Found a solution from this answer: https://stackoverflow.com/a/26611593/5319229

Turns out it has nothing to do with factors.

The bdscale package came in handy.

library(lubridate)
library(ggplot2)
library(dplyr)

day.start = today()

df = data.frame(date = seq.Date(from = today() - days(10), to = today() + days(10), 'day'))
df$day.idx = as.numeric(df$date - day.start + 1)
df$day.idx = ifelse(df$day.idx < 1, df$day.idx + nrow(df), df$day.idx)
df = df %>% arrange(day.idx)
df$value = 1:nrow(df)

ggplot(df) +
geom_point(aes(x = date, y = value)) +
geom_line(aes(x = date, y = value, group = 1))+
bdscale::scale_x_bd(business.dates = df$date, labels = scales::date_format('%b %d'))

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.

how to order the x-axis (in a graph) in chronological order?

As @Allan mentioned it is easy if you keep dates as dates and use scale_x_date to format X-axis and specify their breaks the way you want.

library(dplyr)
library(ggplot2)

final_data %>%
mutate(date_decision_made = as.Date(date_decision_made, "%Y/%m/%d"),
week = format(date_decision_made, "%W-%y")) %>%
group_by(week) %>%
summarise(property_damages_in_dollars = sum(property_damages_in_dollars),
date = first(date_decision_made)) %>%
ggplot() + aes(x = date, y=property_damages_in_dollars) +
geom_line(aes(group=1)) +
scale_x_date(date_labels = "%W-%y", date_breaks = '1 month') +
theme(axis.text.x = element_text(angle = 45))

Sample Image

How do I get R to recognize the appropriate order for Month Year combinations without manually specifying the order?

The reorder function (stats package) can be used to sort factor levels. Here you can use my in the second argument to determine the sort order. So I believe this does what you need:

ggplot(test, aes(x = reorder(month, my(month)), y = values)) + geom_col()


Related Topics



Leave a reply



Submit