Changing tick intervals when x axis values are dates
Upgrade comment
You can change the x-axis labels using scale_x_date
and formats from the scales
package. Using the code from the ggplot2 scale_x_date help pages
library(ggplot2)
library(scales) # to access breaks/formatting functions
# Change Date to date format
aaci$dt <- as.Date(aaci$Date)
# Plot
# You can change the format to suit your requirements
ggplot(aaci, aes(x=dt, y=Average, colour=Species, group=Species)) +
geom_point(size=4) +
geom_line(size=1.3) +
scale_y_continuous(limits = c(0,100), breaks=seq(0,100,10)) +
scale_x_date(date_breaks = "months" , date_labels = "%b-%y")
Changing tick intervals when x-axis values are dates
# load our world in data covid data (https://github.com/owid/covid-19-data/tree/master/public/data/)
owid_data <- read.csv("owid-covid-data.csv")
# subset
df <- subset(owid_data, select=c(iso_code, location, date, total_cases_per_million, new_cases_per_million, new_cases_smoothed_per_million, total_deaths_per_million, new_deaths_per_million, new_deaths_smoothed_per_million, reproduction_rate, stringency_index, excess_mortality, excess_mortality_cumulative_per_million))
df <- subset(df, location == "Australia" | location == "Denmark" | location == "Germany"| location == "Netherlands" | location == "New Zealand"| location == "Sweden"| location == "Switzerland"| location == "United Kingdom")
# Convert "date variable" into class Date variable
class(df$date)
df$date <- as.Date(df$date, "%Y-%m-%d")
class(df$date)
# Ggplot
ggplot(df, aes(x=date, y=total_cases_per_million, group=location))+
geom_line(aes(col=location), size=0.7)+
theme_classic() +
theme(legend.title = element_text(face="bold"), plot.title = element_text(face="bold"), plot.caption = element_text(hjust = 0))+
labs(col = "Country",
title = "Total confirmed cases of COVID-19 per million people",
x = "Date",
y = "COVID-19 cases per million people",
caption = "Source: COVID-19 Data Repository by the Center for Systems Science and Engineering (CSSE) at Johns Hopkins University")+
scale_y_continuous(breaks = seq(0,600000, by=100000), labels = scales::comma)+
scale_x_date(limits = as.Date(c("2020-01-26","2022-05-16")), date_breaks = "1 month", date_minor_breaks = "1 day", date_labels = "%Y-%m-%d")```
MatPlotLib : Changing tick intervals when x axis values are dates
import matplotlib.dates as mdates
months = mdates.MonthLocator() # every month
ax.xaxis.set_major_locator(months)
Try this
Controlling ggplot x-axis ticks that are dates
The scale_x_date(breaks=)
argument can take a function, with which you can programmatically control the labels.
Edit: the use of "4" is hard-coded for my locale; I don't know what other locales may return for Wednesday, so it might be useful to replace 4
below with lubridate::wday("2020-05-20")
(since today is Wednesday).
my_dates <- function(d) {
seq( d[1] + (4 - wday(d[1])) %% 7, d[2] + 6, by = "week")
}
# ...
scale_x_date(breaks = my_dates, date_labels = "%b %d") +
#...
Updated code (sans subtitle=
, since we lack COVtests
):
g <- stateWeekly %>% ggplot(aes(x = as.Date(weekStarting))) +
geom_col(aes(y=100*dailyTest), size=0.75, color="darkblue", fill="white") +
geom_line(aes(y=posRate), size = 0.75, color="red") +
scale_y_continuous(name = "Test Positivity Rate",
sec.axis = sec_axis(~./100, name="Percent of Pop Tested")) +
scale_x_date(breaks = my_dates, date_labels = "%b %d") +
labs(x = "Week Starting",
title = "COVID-19 Testing",
# subtitle = paste("Data as of", format(max(as.Date(COVtests$date)), "%A, %B %e, %y")),
caption = "HQ AFMC/A9A \n Data: The COVID Tracking Project (https://covidtracking.com)") +
theme(plot.title = element_text(size = rel(1), face = "bold"),
plot.subtitle = element_text(size = rel(0.7)),
plot.caption = element_text(size = rel(1)),
axis.text.y = element_text(color='red'),
axis.title.y = element_text(color="red"),
axis.text.y.right = element_text(color="blue"),
axis.title.y.right = element_text(color="blue"),
axis.text.x = element_text(angle = 45,hjust = 1),
strip.background =element_rect(fill="white"),
strip.text = element_text(colour = 'blue')) +
coord_cartesian(ylim=c(0,75)) +
facet_wrap(~ state)
How to show date x-axis labels every 3 or 6 months in ggplot2
First convert date by: df$Month_Yr <- as.Date(as.yearmon(df$Month_Yr))
Then use this can solve the issue:
ggplot(reshaped_median, aes(x= Month_Yr, y = value))+
geom_line(aes(color = Sentiments)) +
geom_point(aes(color = Sentiments)) +
#Here you set date_breaks ="6 month" or what you wish
scale_x_date(date_labels="%b-%d",date_breaks ="3 month")+
labs(title = 'Change in Sentiments (in median)', x = 'Month_Yr', y = 'Proportion of Sentiments %') +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
Related Topics
Grouping with Custom Geom Fails - How to Inspect Internal Object from Draw_Panel()
Insert Images Using Knitr::Include_Graphics in a for Loop
R: Adding Alpha Bags to a 2D or 3D Scatterplot
How to Change Strip.Text Labels in Ggplot with Facet and Margin=True
How to Install the R Package Rgl on Ubuntu 9.10, Using R Version 2.12.1
Using 'Fread' to Import CSV File from an Archive into 'R' Without Extracting to Disk
How to Summarizing Data Statistics Using R
Colons Equals Operator in R? New Syntax
Shiny + Ggplot: How to Subset Reactive Data Object
How Do Add a Column in a Data Frame in R
When Writing My Own R Package, I Can't Seem to Get Other Packages to Import Correctly
Using Get Inside Lapply, Inside a Function
Use a Factor Column in "By" and Do Not Drop Empty Factors
R How to Extract First Row of Each Matrix Within a List
Fill Area Between Two Lines, with High/Low and Dates
Rcmdr Launch Error in Yosemite (Os X 10.10)
Create All Possible Combiations of 0,1, or 2 "1"S of a Binary Vector of Length N