首页 > 解决方案 > ggplot2按形状分隔图例

问题描述

# Data:  
zz <- "Small Large  Lat  Long 
1       51   2       11    10 
2       49   0       12    11  
3       77   7       13    13  
4       46   5       12    15     
5       32   6       13    14      
6       54   3       15    17
7       68   0       14    10
8       39   5       12    13"

Data <- as.data.frame(read.table(text=zz, header = TRUE))

我有一个连续变量,一个比率(小/大),我正在成功绘制。

虽然,“大”变量中存在一些 0。发生这种情况时,我只想绘制“小”数字,因为比率是不可能的。为此,我有以下内容:

ratio.both <- Data %>% 
  filter(Large > 0) %>% 
  mutate(Ratio = Small/Large)

only.sml<- Data %>% 
  filter(Large < 1)

然后我将两者都绘制在同一张图上(按经纬度数据):

ggplot() +
  geom_point(data = ratio.both,
             aes(x = Long,
                 y = Lat,
                 size = Ratio),
             stroke = 0,
             colour = '#3B3B3B',
             shape=16) +
  #
  geom_point(data = only.sml,
             aes(x = Long,
                 y = Lat,
                 size = Small,
                 shape=1),
             stroke = 1,
             shape=1)

注意形状的不同。这绘制了以下内容

不是最好的图表,但演示了示例 不是最好的图表,但演示了示例

那些是比率(填充)和那些只是小值之间的区别在地图上很清楚,但在图例中很难。

我想要传说中的以下内容:

   #Title
   Size = both.ratio$Ratio,
   Shape/fill = Ratio or small value #whichever is easier

标签: rggplot2

解决方案


使用内置的美学映射在表格中使用变量来对比数据要容易得多,而不是为小数据和大数据创建单独的几何图形。例如,您可以创建一个新变量来检查该数据点是属于大“类型”还是属于小“类型”。然后,您可以在美学中映射形状、颜色、大小或任何您想要的东西,并可选择手动为这些添加比例(如果需要)。

Data %>% 
  mutate(is_large = ifelse(Large > 0, "Ratio", "Small"),

         size = ifelse(is_large == "Large", Small/Large, Small)) %>%
  ggplot(aes(Long, Lat, 
             size = size, 
             shape = is_large)) +
  geom_point() +
  scale_shape_manual(values = c("Ratio" = 16, "Small" = 1), 
                     name = "Size") +
  scale_size_continuous(name = "Ratio/small value") 

在此处输入图像描述

或者,如果您想按点颜色进行对比:

Data %>% 
  mutate(is_large = ifelse(Large > 0, "Ratio", "Small"),

         size = ifelse(is_large == "Large", Small/Large, Small)) %>%
  ggplot(aes(Long, Lat, 
             size = size, 
             color = is_large)) +
  geom_point() +
  scale_color_manual(values = c("Ratio" = "blue", "Small" = "red"), 
                     name = "Size") +
  scale_size_continuous(name = "Ratio/small value") 

在此处输入图像描述


推荐阅读