【问题标题】:如何删除 Y 轴标题并用图例标题替换它们
【发布时间】:2022-01-23 12:36:40
【问题描述】:

我 2 周前刚开始 R 编程,我有一个带有 1 个 x 轴和 2 个 y 轴的案例研究图……我在 48 小时内尽我所能用 Legend 替换 Title……但我做不到找出问题所在,希望我能得到你们的帮助。

剧情:

ggplot(libya_covid, aes(x=date)) +
  
  geom_line( aes(y=new_tests), size=2, color='blue') + 
  geom_line( aes(y=new_cases / 1), size=2, color='darkorange') +
  
  xlab("Date")+
  
  scale_y_continuous(
    
    # Features of the first axis
    name = "New Tests",
    
    # Add a second axis and specify its features
    sec.axis = sec_axis(~.*1, name= "New Cases")
  ) + 
  
  theme_bw() +
  
  theme(
    axis.title.y = element_text(color = 'blue', size=13),
    axis.title.y.right = element_text(color = 'darkorange', size=13)
  ) +
  
  ggtitle("New Tests Versus New Cases Analysis")

现在我只想从左右删除 Y 标题并在左上角添加简单图例

提前致谢。

【问题讨论】:

  • 欢迎堆栈溢出。请通过粘贴数据样本使您的问题可重现:使用dput(head(your_data_sample, n)) 其中n 足以证明问题的数据。这使得其他人更容易复制数据以测试和验证解决方案。 minimal reproducible example

标签: r ggplot2


【解决方案1】:

在 ggplot2 中,图例反映了美学或尺度。这就是说,如果你想拥有一个传奇,你必须在美学上进行映射。

要获得描绘不同颜色线条的图例,您可以在颜色美学上映射一个常量值,然后使用 scale_color_manual 将所需颜色分配给这些常量。

要摆脱标签,从scale_y_continious 中删除name=s 并使用labs 设置y=NULL,这意味着删除y 轴标题。最后,您可以通过theme 选项legend.positionlegend.justification 定位图例:

library(ggplot2)

#### Use economics dataset as example data
libya_covid <- ggplot2::economics
names(libya_covid)[4:5] <- c("new_tests", "new_cases")
####

ggplot(libya_covid, aes(x=date)) +
  geom_line( aes(y=new_tests, color='New Tests'), size=2) + 
  geom_line( aes(y=new_cases / 1, color='New Cases'), size=2) +
  labs(x = "Date", y = NULL, color = NULL, title = "New Tests Versus New Cases Analysis") +
  scale_y_continuous(
    sec.axis = sec_axis(~.*1)
  ) + 
  scale_color_manual(values = c("New Tests" ='blue', "New Cases" ='darkorange')) +
  theme_bw() +
  theme(
    axis.title.y = element_text(color = 'blue', size=13),
    axis.title.y.right = element_text(color = 'darkorange', size=13),
    legend.position = c(0.05, .95),
    legend.justification = c(0.05, .95)
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    相关资源
    最近更新 更多