【问题标题】:insert legend color square into r ggplot axis label将图例颜色方块插入 r ggplot 轴标签
【发布时间】:2017-11-20 20:38:26
【问题描述】:

我找到了很多关于如何在 R 中的 ggplot 中将特殊字符和希腊字母插入轴标签的优秀文档,但没有将图例颜色粘贴到轴标签中。我正在创建一个带有稍微复杂的 x 轴的图形,一位合作者建议在轴标签文本中使用彩色正方形(与图例相同)格式化轴,以便读者可以参考哪个轴标签指的是哪个数据系列。

这是人物图例当前的样子:

[橙色广场]系列一

【蓝方】系列2

这就是我希望 x 轴标签的样子:

范围以公里 [橙色广场] 或公里/年 [蓝色广场] 为单位

是否可以在 R 中进行这种图形操作,或者我是否需要在其他一些图像处理软件中创建这种标签?这是我正在使用的绘图代码,带有一些假数据:

SERIES1 <- as.data.frame(sample(1:100, 100, replace=TRUE)) %>% mutate(source="SERIES1") 
SERIES2 <- as.data.frame(sample(1:1000, 100, replace=TRUE)) %>% mutate(source="SERIES2")
SERIES3 <- as.data.frame(sample(1:10000, 100, replace=TRUE)) %>% mutate(source="SERIES3")
colnames(SERIES1) <- c("value","source")
colnames(SERIES2) <- c("value","source")
colnames(SERIES3) <- c("value","source")
gg_df <- rbind(SERIES1, SERIES2, SERIES3)

fig1A <- ggplot(gg_df) + 
  geom_density(alpha=0.5, size=0.2, aes(x=value, y=..scaled.., fill=factor(source, labels=c('SERIES1','SERIES2','SERIES3')))) + 
  scale_x_continuous(limits=c(0,16000), breaks=c(seq(0, 16000, by=2000))) + 
  labs(x='Extent (km) or (km/dec)',y='Density') +
  theme_bw() +
  theme(legend.position=c(0.8, 0.85), legend.title=element_blank()) + 
  scale_fill_brewer(type='qual',palette='Dark2')

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    cowplot 包具有很好的在 ggplots 上进行注释的功能

    require(cowplot)
    

    首先,在 x 标签上添加空格,为正方形腾出空间

    fig1A <- ggplot(gg_df) + 
      geom_density(alpha=0.5, size=0.2, aes(x=value, y=..scaled..,
            fill=factor(source, labels=c('SERIES1','SERIES2','SERIES3')))) + 
      scale_x_continuous(limits=c(0,16000), breaks=c(seq(0, 16000, by=2000))) + 
      labs(x='Extent (km)     or (km/dec)     ',y='Density') + 
      theme_bw() +
      theme(legend.position=c(0.8, 0.85), legend.title=element_blank()) + 
      scale_fill_brewer(type='qual',palette='Dark2')
    

    为您的方块制作一个包含 x 和 y 位置的数据框

    squares <- data.frame(x = c(0.53, 0.75),  y = c(0.017,0.017))
    

    使用cowplot 中的ggdraw 函数绘制图形,然后在其上标注正方形。与 ggplot 中的annotategeom_rect 不同,它们只允许在绘图区域内进行注释,您可以使用cowplot 在图形上的任何位置进行注释。正方形的位置是使用从左到右和从下到上的 0 - 1 比例给出的 - 您可能必须根据保存图形的大小来调整数字。

    ggdraw(fig1A) + 
    geom_rect(data = squares, aes(xmin = x, xmax = x + .02, 
                              ymin = y, ymax = y + .02),
            fill = c("orange", "blue"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 2019-04-13
      • 2021-01-09
      • 2023-01-09
      相关资源
      最近更新 更多