0

我在 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")

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

对于“销售”列值 <=1.9;大小为 5,

对于 1.9 < 销售价值 <= 10;大小范围为 10 到 20,

对于 10 < 销售价值 <= 20;大小为 25

并且 sale_value > 20;大小将是 30。

我无法弄清楚这是如何实现的,甚至可能与否。

4

2 回答 2

1

您可以明确指定尺寸:

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 的增加而增加。如果这不是您想要的,您可以将值的平方根乘以品味常数,到获得与面积成比例的尺寸。

于 2021-03-20T20:55:31.923 回答
1

此代码可能对您有帮助:

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"))

要根据值填充不同的颜色,您需要一个同时采用填充和颜色的形状(pch 21-25)。然后,您可以将填充美学映射到利润 < 2 并将颜色设置为始终为红色。我scale_fill_manual用来定义我想要的颜色。

于 2021-03-20T21:09:24.233 回答