如何在 R ggplot 中动态更改圆形的大小和填充颜色?

How to change size and fill color of a circular shape dynamically in R ggplot?

我在 R 中有一个示例数据框。

df <- data.frame(product_id= c("A","A","A","B","B","B","C","C"), year = c("2019", "2020", "2021", "2019", "2020", "2021", "2019", "2020"), profit=c(1.5, 2.2, 2.3, 1.4, 1, 16, 1.9, 25), sale = c(1.2, 1.8, 1.9, 2.0, 1.6, 20.0, 3.0, 33.2))

我正在尝试在 ggplot 中绘制三个单独的图表,其中 y='year'、x='profit' 并且数据将按 product_id 过滤。所有 geom_point 都将是圆形。这可以通过产品 A 的以下代码来实现:

library(ggplot2)
library(dplyr)
ggplot(df) +
  geom_point(data= df %>% filter(product_id =='A'), aes(x=year, y=profit, size=sale), shape = 16, color='Red') +
  scale_size_continuous(range = c(5, 10), guide = FALSE) +
  labs(x = "Year", y = "Profit")

但是对于自定义,如果y轴值(利润)小于2.0,我愿意改变圆的填充颜色。边框应为红色作为原始颜色,但填充颜色应为黄色。对于上图,2019 年的点将是红色边框和黄色填充颜色。我已经尝试过以下方法,但它不起作用:

library(ggplot2)
library(dplyr)
ggplot(test_df) +
  geom_point(data= test_df %>% filter(product_id =='A'), aes(x=year, y=profit, size=sale), shape = 16, color='Red') +
  scale_size_continuous(range = c(5, 10), guide = FALSE) +
  scale_colour_manual(name = 'profit < 2', values = setNames(c('Yellow','Red'),c(T, F)), guide = FALSE) +
  labs(x = "Year", y = "Profit")

另一个问题是所有三个图形的圆形大小都没有保持标准的相对大小。我正在尝试开发一个标准尺寸比例,例如

对于'sale'列值<=1.9;大小将为 5,

1.9 < sale_value <= 10;大小范围将是 10 到 20,

10 < sale_value <= 20;尺寸将为 25

并且 sale_value > 20;尺寸将为 30。

我不知道这是如何实现的,甚至不知道这是否可能。

您可以明确指定尺寸:

df %>%
  mutate(size = case_when(
    sale <= 1.9 ~ 5,
    sale <= 10 ~ sale * 2,
    sale <= 20 ~ 25,
    sale > 20 ~ 30
  )) -> df2

然后映射 profit < 2 进行填充,使用您的颜色定义:

ggplot(df2) +
  geom_point(data= df2 %>% filter(product_id =='A'), color = "red",
             aes(x=year, y=profit, size=size, fill = profit < 2), shape = 21) +
  scale_size_identity() +
  scale_fill_manual(name = 'profit < 2', values = setNames(c('Yellow','Red'),c(T, F)), guide = FALSE)  +
  labs(x = "Year", y = "Profit")

请注意,默认情况下,尺寸美学映射到点半径,这意味着感知区域将随着该值增加 ^ 2。如果这不是您想要的,您可以映射您的值的平方根,乘以 a口味常数,以获得与面积成比例的大小。

此代码可能对您有所帮助:

df2 <- data.frame(
  product_id = c("D", "D", "D", "D"), 
  year = c("2020", "2020", "2020", "2020"), 
  profit = c(1.5, 15, 25, 35), 
  sale = c(1.5, 15, 25, 35) 
)

df3 <- rbind(df, df2)

ggplot(df3) +
  aes(x = year, y = profit, fill = profit < 2) + 
  facet_wrap(~ product_id) +
  geom_point(
    aes(size = sale), 
    color = "red", 
    pch = 21
  ) +
  scale_fill_manual(values = c("red", "yellow"))

要根据值填充不同的颜色,您需要一个同时具有填充和颜色的形状(第 21-25 页)。然后,您可以将填充美学映射到 profit < 2 并将颜色设置为常亮红色。我使用 scale_fill_manual 来定义我想要的颜色。