Home > Net >  Only show maximum and minimum dates/values for x and y axis label in ggplot2 plot
Only show maximum and minimum dates/values for x and y axis label in ggplot2 plot

Time:11-16

Based on sample time series data and plot code blow:

df <- structure(list(date = structure(c(18901, 18902, 18903, 18904, 
18905, 18906, 18907, 18908, 18909, 18910, 18911, 18912, 18913, 
18914), class = "Date"), value = c(190.3, 174.9, 163.2, 168.4, 
168.6, 168.2, 163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 
177.9), type = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 
3L, 3L, 3L)), row.names = c(NA, -14L), class = "data.frame")
df$type <- as.factor(df$type)
df$date <- as.Date(df$date)
ggplot(df, aes(x=date, y=value, group=type, 
            color = type, fill = type))   
  geom_area(alpha=0.4)  
  geom_hline(yintercept=max(df$value), linetype='dotted', col = 'red') 
  scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"), 
                     aesthetics = c("color", "fill"), name = "type")  
  theme(
    # axis.text.x=element_blank(),
    axis.title.x=element_blank(),
    axis.title.y=element_blank())

Out:

enter image description here

I would like to go further by showing only maximum and minimum values for y axis labels and starting date and ending date for x axis labels. The effect will similar to the following image.

enter image description here

How could I do that with ggplot2? Sincere thanks.

CodePudding user response:

You could achieve your desired result by setting the breaks of the scales equal to the range of the variables mapped on x and y:

Notes:

  1. If you want to start the y-scale at zero you could do breaks = c(0, max(df$value)).

  2. Instead of removing the axis titles via theme you could simply do it via labs.

library(ggplot2)
ggplot(df, aes(
  x = date, y = value, group = type,
  color = type, fill = type
))  
  geom_area(alpha = 0.4)  
  scale_y_continuous(breaks = range(df$value))  
  scale_x_date(breaks = range(df$date))  
  scale_color_manual(
    values = c("1" = "gray", "2" = "red", "3" = "blue"),
    aesthetics = c("color", "fill"), name = "type"
  )  
  labs(x = NULL, y = NULL)

  • Related