I have a visualization that contains a barplot and a lineplot with two different scales. The x-axis is a time based object.
The data the plot is derived from this dataframe:
count_coi rel year
1: 55 12.06 2000-01-01
2: 39 6.82 2005-01-01
3: 94 8.22 2010-01-01
4: 128 6.31 2015-01-01
Count-Coi is represendet by barplots and rel is represented by the lineplots. Currently years are shown, but the years actually represent time periods like this "2000-2004". So basically what I need is to change the labels of the x-axis from years to periods without losing my time based object. Instead of 2000 it should show:
2000-2004
But, if I change the data I lose my lineplot because it needs a time based object.
Here is my ggplot code:
ggplot(data, aes(x=year)) +
geom_bar(aes(y=count_coi), stat="identity", size=.2, fill=bar_col, color="black", alpha=.7) +
geom_line(aes(y=rel * coeff), size=1, color=line_col) +
scale_y_continuous(
# Features of the first axis
name = "",
# Add a second axis and specify its features
sec.axis = sec_axis(~./coeff, name="")) +
xlab(label = "") +
theme_minimal() +
theme(
axis.title.y = element_text(color = bar_col, size=13),
axis.title.y.right = element_text(color = line_col, size=13)
)
So how do I override the labels? Help would be appreciated...
Use scale_x_date()
and the labels=
argument to relabel the axis:
# just in case data$year is not formatted as a Date...
data$year <- as.Date(data$year, format='%Y-%m-%d')
# your original plot code here... +
scale_x_date(
breaks=data$year,
labels = c('2000-2004', '2005-2009','2010-2014','2015-2019'))
You will notice that I also define breaks=
in addition to labels=
, since this is required that if you specify the labels, you need to also specify the breaks to use (and the two must be of equal length). In this case, no values of data$year
are duplicated and are in order in your dataset, so it is advantageous to define breaks=data$year
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.