简体   繁体   English

更改 x 轴刻度

[英]Change x-axis ticks

Good afternoon everyone,大家下午好,

I am having difficulties plotting a time series with ggplot.我在用 ggplot 绘制时间序列时遇到困难。 I have a time series with daily data from 2020-01-30 to 2020-10-22.我有一个时间序列,其中包含从 2020-01-30 到 2020-10-22 的每日数据。 When I plot the data with the following code, I get an x-axis, which is not at all readable:当我使用以下代码 plot 数据时,我得到一个 x 轴,它根本不可读:

plot_cases <- ggplot(NULL, aes(x= Date, y= Count)) +
  xlab("Time") + ylab("Number of Cases") +
  scale_y_continuous(limits=c(0, 2000)) +
  scale_x_discrete() +
  geom_line(data = P_cases_reduced_aggregated_female, aes(colour = P_cases_reduced_aggregated_female$Sex, group = 1)) +
geom_line(data = P_cases_reduced_aggregated_male, aes(colour = P_cases_reduced_aggregated_male$Sex, group = 1)) +
  scale_color_manual(values=c("#FF00FF", "#000FFF"))

Therefore, I would like to only have the abbreviation of the months represented such as "Apr", "Jul", "Oct".因此,我只想使用代表月份的缩写,例如“Apr”、“Jul”、“Oct”。 However, as I use the following code, I don't get any x-axis graduation anymore...但是,当我使用以下代码时,我不再获得任何 x 轴刻度...

plot_cases <- ggplot(NULL, aes(x= Date, y= Count)) +
  xlab("Time") + ylab("Number of Cases") +
  scale_y_continuous(limits=c(0, 2000)) +
  scale_x_discrete(breaks = seq(as.Date("2020-01-30"), as.Date("2020-10-22"), by = "month")) +
  geom_line(data = P_cases_reduced_aggregated_female, aes(colour = P_cases_reduced_aggregated_female$Sex, group = 1)) +
geom_line(data = P_cases_reduced_aggregated_male, aes(colour = P_cases_reduced_aggregated_male$Sex, group = 1)) +
  scale_color_manual(values=c("#FF00FF", "#000FFF"))

As one of you a solution to this?作为你们中的一员解决这个问题? I have checked the previous questions about scale_x_discrete but I still don't get how to do the relevant changes.我已经检查了之前关于 scale_x_discrete 的问题,但我仍然不知道如何进行相关更改。

Thank you so much in advance.非常感谢你提前。

Following the great advice of @AllanCameron and @r2evans first transform to date in x-axis to date and then use scale_x_date() .遵循@AllanCameron@r2evans的重要建议,首先将 x 轴转换为日期,然后使用scale_x_date() No output showed due to lack of data:由于缺少数据,没有显示 output:

library(ggplot2)
#Code
plot_cases <- ggplot(NULL, aes(x= Date, y= Count)) +
  xlab("Time") + ylab("Number of Cases") +
  scale_y_continuous(limits=c(0, 2000)) +
  scale_x_date(date_labels="%B-%d",breaks = '7 days') +
  geom_line(data = P_cases_reduced_aggregated_female,
            aes(colour = P_cases_reduced_aggregated_female$Sex, group = 1)) +
  geom_line(data = P_cases_reduced_aggregated_male,
            aes(colour = P_cases_reduced_aggregated_male$Sex, group = 1)) +
  scale_color_manual(values=c("#FF00FF", "#000FFF"))+
  theme(axis.text.x = element_text(angle=90))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM