[英]How to show date x-axis labels every 3 or 6 months in ggplot2
我使用以下代碼生成 plot:
ggplot(reshaped_median, aes(x= Month_Yr, y = value))+
geom_line(aes(color = Sentiments)) +
geom_point(aes(color = Sentiments)) +
labs(title = 'Change in Sentiments (in median)', x = 'Month_Yr', y = 'Proportion of Sentiments %') +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
但是你可以注意到 x 軸上的日期標簽太密集了,所以如果我想它顯示一個季度或半年的日期(每 3 或 6 個月)。
Month_Yr
的值采用格式%Y-%m
。
我怎么能那樣做? 謝謝。
首先轉換日期: df$Month_Yr <- as.Date(as.yearmon(df$Month_Yr))
然后使用這個可以解決問題:
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))
這是另一種方式。 使用scale_x_date
,您可以輕松地操縱 x 軸上的中斷。
library(ggplot2)
library(tibble)
data <- tibble(
Month_Yr = seq.Date(from = as.Date("2010/01/01"), to = as.Date("2020/01/31"), by = "month"),
Value = runif(121, min = 0, max = 150)
)
p <- ggplot(data = data, aes(x = Month_Yr, y = Value)) +
geom_point() +
theme(axis.text.x = element_text(angle = 60, hjust = 1)) +
scale_x_date(date_breaks = "6 months")
p
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.