调整ggplot中散点图的大小

时间:2019-03-18 18:41:03

标签: r ggplot2 size

我有数据:

+-----------+---------+----------+
| AGE_group | mean_y  |  count_y |
+-----------+---------+----------+
|         1 |   0.141 |     1115 |
|         2 |   0.196 |     1043 |
|         3 |   0.202 |     1093 |
|         4 |   0.114 |     1123 |
+-----------+---------+----------+

我使用ggpplot:

g_age <- ggplot(AGE_group_df, aes(AGE_group, mean_y, group = 1)) +
  geom_line(size=1, color='blue') +
  geom_point(aes(size=AGE_group_df$count_y), color='darkblue') +
  labs(x = 'Age Group',
       y='% Subscribe',
       title='Age Group and Subscribe Rate',
       size='# Customer')
g_age

enter image description here

问题:第二点的大小(计数为1043)与其他点相比很小。

问题:如何更改积分大小? (我想使所有4个点的大小几乎相等),同时保持原始计数单位。

非常感谢您。

1 个答案:

答案 0 :(得分:1)

您可以(至少)使用三种方法

  1. 使用scale_size_areascale_size_area()
  2. 将范围参数用于scale_sizescale_size(range = 4:5)
  3. 将limit自变量设置为0到最大值count_yscale_size(limits = c(0, max(AGE_group_df$count_y))

在此更详细:一种选择是使用scale_size_area

AGE_group_df <- data.frame(AGE_group = 1:4, 
                           mean_y = c(0.141, 0.196, 0.202, 0.114), 
                           count_y = c(1115, 1043, 1093, 1123))


ggplot(AGE_group_df, aes(x = AGE_group, y = mean_y, size = count_y)) +
  geom_line(size=1, color='blue') +
  scale_size_area(breaks = round(seq(min(AGE_group_df$count_y),
                  max(AGE_group_df$count_y), length.out = 4), 0)) + 
  geom_point(color='darkblue') +
  labs(x = 'Age Group',
       y='% Subscribe',
       title='Age Group and Subscribe Rate',
       size='# Customer')

enter image description here 另一个在scale_size中手动定义范围参数的方法:

ggplot(AGE_group_df, aes(x = AGE_group, y = mean_y, size = count_y)) +
  geom_line(size=1, color='blue') +
  scale_size(breaks = round(seq(min(AGE_group_df$count_y), 
             max(AGE_group_df$count_y), length.out = 4), 0), range = 4:5) + 
  geom_point(color='darkblue') +
  labs(x = 'Age Group',
       y='% Subscribe',
       title='Age Group and Subscribe Rate',
       size='# Customer')

enter image description here 第三,将scale_size的下限设置为0:

ggplot(AGE_group_df, aes(x = AGE_group, y = mean_y, size = count_y)) +
  geom_line(size=1, color='blue') +
  scale_size(breaks = round(seq(min(AGE_group_df$count_y), 
             max(AGE_group_df$count_y), length.out = 4), 0), 
             limits = c(0, max(AGE_group_df$count_y))) + 
  geom_point(color='darkblue') +
  labs(x = 'Age Group',
       y='% Subscribe',
       title='Age Group and Subscribe Rate',
       size='# Customer')

请注意,您可以在aes函数中定义大小。我添加了休息时间以显示最小值和最大值,但这不是必需的。这只是一个额外的壮举。