How can I order the months chronologically in ggplot2 short of writing the months out?
Use the built-in month.name
or month.abb
variable to specify the levels of your factor in the correct order. In this case, you have abbreviations so month.abb
is appropriate.
your_data$month = factor(your_data$month, levels = month.abb)
I think creating the factor in the correct order is the best way, but you can also just order the axis using the limits
argument of the discrete scale (see ?discrete_scale
for more info).
+ scale_x_discrete(limits = month.abb)
Locales
If you are in a non-English locale, you can construct your own month name constants with a little date formatting (basically stolen from Brian Ripley in this R-Help thread):
month.name.loc = format(ISOdate(2004, 1:12, 1), "%B")
month.abb.loc = format(ISOdate(2004, 1:12, 1), "%b")
If you want to use month names/abbreviations from a different locale than you're in, the withr
package is useful.
How to plot into month-year order instead of alphabetic order in ggplot?
Using lubridate
to make a date from the month column
monthplot <- monthplot %>%
mutate(date = lubridate::dmy(month, truncated = -1))
ggplot(monthplot, aes(x = date, y = visits)) +
geom_col(fill = "#0073C2FF") +
geom_text(aes(label = visits), vjust = -0.3) +
theme_pubclean()
If you want to change how the date is shown, use scale_x_date
and set the date_breaks
and/or date_labels
arguments
Arrange the labels of monthly time series in ggplot, R
Setting month
as a factor and specifying the order of the levels (with the argument levels
) solves the issue, as below.
month<-c("May","June","July","August","September","May","June","July","August","September")
year<-c("1985","1985","1985","1985","1985","1986","1986","1986","1986","1986")
value<-c(2,6,4,5,9,7,2,6,5,4)
df<-data.frame(month,year,value)
df$month <- factor(df$month, levels = c("May", "June", "July", "August", "September"))
ggplot(df, aes(x=month, y=value,group=year))+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
,panel.grid.minor = element_blank()) +ylim(0,10)+labs(x="Month",y=expression(bold(paste("variable here"))))+
theme(axis.title.x = element_text(face="bold", size=12),axis.text.x = element_text(size=9))+
theme(axis.title.y = element_text(face="bold", size=12),axis.text.y = element_text(size=9))+theme(axis.text.x = element_text(angle = 45, hjust = 1))+
geom_line(linetype="solid", size=1)+geom_point(color="gray7", size=2,shape=15)
sorting months in R with count or summarise
Since you have no sample data provided, I can't test if it really works in your specific case. Converting your months-data to a factor works, but you'll have to specify the names of the months first (in the language of your data), as R doesn't know how you want them to be ordered. Thus, creating a factor without defining the levels will only lead to alphabetical order, which isn't correct for months.
library(dplyr)
result <- mydata %>%
mutate(ordered_months = factor(months(as.Date(orderdate)),
levels=c("January", "February", ...))) %>% # insert all month-names here
count(ordered_months)
result
...should work.
Creating ggplot with segregated columns
You should try to add scale_x_discrete
functions and pass the ordering in the argument limits
:
ggplot(df, aes(Month.of.Death, fill=Month.of.Death))+
geom_bar(color="black",fill="brown3")+
theme(text = element_text(size=15),axis.text.x = element_text(angle=90, hjust=1))+
labs(title = "Liczba śmierci dziennikarzy w danym miesiącu", x="Miesiąc", y="Liczba dziennikarzy")+
scale_x_discrete(limits = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December","Unknown"))
If this is not working, please consider to add a reproducible example of your dataset as specified here: How to make a great R reproducible example
Can I chronologically order dates as characters in R?
openingData %>%
mutate(dateOpened = as.Date(dateOpened,"%m/%d/%y")) %>%
arrange(dateOpened) %>%
mutate(id = factor(row_number(),labels = dateOpened)) %>%
ggplot() +
geom_col(mapping = aes(x = id, y = daysPrior))+
labs(x = "Date Opened", y = "Days prior to opening at or above 11.0")
Sorting months in R
You could always convert your data to a factor. For example, suppose we have
x = c("January", "February", "March", "January")
then to convert to a factor, we have:
x_fac = factor(x, levels = month.name)
which on sorting gives:
R> sort(x_fac)
[1] January January February March
12 Levels: January February March April May June July August ... December
Boxplot with ggplot2 in R - returns by month
First, add new column month
to your original data frame containing month.name
(built-in constant in R) and use it as factor. It is import to set also levels=
inside the factor()
to ensure that months are arranged in chronological order not the alphabetical.
Then melt this data frame from wide format to long format. In ggplot()
use month
as x values and value
as y.
df$month<-factor(month.name,levels=month.name)
library(reshape2)
df.long<-melt(df,id.vars="month")
ggplot(df.long,aes(month,value))+geom_boxplot()
Related Topics
Can't Execute Rsdriver (Connection Refused)
Adding Percentage Labels to a Bar Chart in Ggplot2
Sort Columns of a Dataframe by Column Name
Apply a Function to Every Row of a Matrix or a Data Frame
Duplicates in Multiple Columns
How to Generate a Matrix of Combinations
Drawing Pyramid Plot Using R and Ggplot2
How to Sort Letters in a String
Adaptive Moving Average - Top Performance in R
Remove/Collapse Consecutive Duplicate Values in Sequence
Run a for Loop in Parallel in R
Shiny: Differencebetween Observeevent and Eventreactive
Add Error Bars to Show Standard Deviation on a Plot in R