ggplot:定义 sexond 轴更改第一轴的格式

ggplot: defining sexond axis changes format of first axis

我使用 ggplot2 绘制日期如下:

df <- data.frame(date= sample(seq(from=as.Date("2015-01-01"),length.out=100,by="day")))
my_plot <- ggplot(df, aes(date)) +
  geom_density()
my_plot

这看起来符合预期。但是一旦我定义了一个 sexond 轴,第一个变化的格式:

my_plot +
  scale_x_continuous(sec.axis = sec_axis(~ . , name = "test", breaks = NULL, labels = NULL))

在此示例中,第二个轴可以替换为 labs(title= "test")。这只是一个最小的可重现示例。无论我们如何定义第二个轴,第一个 x 轴不再显示月份,而是显示数字。如何在不更改第一个轴格式的情况下定义第二个轴?

导致问题的不是第二个轴,而是您指定的是 scale_x_continuous 而不是 scale_x_date:

my_plot +
  scale_x_date(sec.axis = sec_axis(~ . , name = "test", breaks = NULL, labels = NULL))