将两个具有不同数据点的散点图合并

4

我有一个需求,想要在同一绘图区域中组合两个不同的散点图。一个散点图是基于指标1的,另一个散点图是基于指标2的。 在R中是否可行? 我已经添加了数据集和代码,但不确定如何在同一图中合并这两个散点图。

df1 <- data.frame(Product = c("A","B","C"),
                  ProductMetric =  c("85","90","92"),
                  CategoryMetric = c("83"),
                  Category = c("AAA"))
df1
ggplot(data=df1, mapping= aes(x=Category,y= ProductMetric))+ geom_point(size=5)+
  ggplot(data=df1, mapping= aes(x=Category,y= CategoryMetric))+ geom_point(size=5)

基本上,在合并结果后,同一张图表中应该有4个圆圈。我想在同一张图表中用圆圈显示产品平均值和类别平均值,这样最终用户只需查看图表即可比较产品平均值和类别平均值。
敬礼, Akash

感谢您的快速回复。非常感谢您的帮助。 - Akash
2个回答

5
您只需要使用`tidyr`包中的`gather`函数将数据从`宽`格式转换为`长`格式即可。点击此处了解更多信息。
library(dplyr)  
library(tidyr)
library(ggplot2)

df1 <- data.frame(Product = c("A","B","C"),
                  ProductMetric =  c("85","90","92"),
                  CategoryMetric = c("83"),
                  Category = c("AAA"))
df1

#>   Product ProductMetric CategoryMetric Category
#> 1       A            85             83      AAA
#> 2       B            90             83      AAA
#> 3       C            92             83      AAA

df1_long <- df1 %>% 
  gather(key, value, -Category, -Product)
df1_long

#>   Product Category            key value
#> 1       A      AAA  ProductMetric    85
#> 2       B      AAA  ProductMetric    90
#> 3       C      AAA  ProductMetric    92
#> 4       A      AAA CategoryMetric    83
#> 5       B      AAA CategoryMetric    83
#> 6       C      AAA CategoryMetric    83

ggplot(df1_long, aes(x = Category, y = value, color = key)) + geom_point(size = 5)

编辑:为了保持 Category Ave 的颜色为红色,同时根据产品数量动态更改每个 Product 的颜色和图例。
myCol <- c(RColorBrewer::brewer.pal(length(unique(df1$Product)), "Set2"), "red")

ggplot(df1, aes(x = Product, y = ProductMetric, color = Product)) + geom_point(size = 5) +
  geom_point(data = df1, aes(y = CategoryMetric, color = "Category Ave"), size = 5) +
  scale_color_manual("Legend", 
                     labels = c(paste0("Product ", df1$Product), "Category Ave"),
                     values = myCol)

ggplot(df1, aes(x = Category, y = ProductMetric, color = Product)) + geom_point(size = 5) +
  geom_point(data = df1, aes(y = CategoryMetric, color = "Category Ave"), size = 5) +
  scale_color_manual("Legend", 
                     labels = c(paste0("Product ", df1$Product), "Category Ave"),
                     values = myCol)

这段内容是在2018年3月31日由reprex包(v0.2.0)创建的。


我想要动态地为每个产品更改颜色,并保持类别平均值为“红色”。 - Akash
我的意思是为3种产品使用三种不同的颜色.. :) - Akash

3
我们可以添加一个新的geom_point层,并指定datadf1yCategoryMetric
library(ggplot2)

ggplot(data = df1, mapping = aes(x = Category, y = ProductMetric)) + 
  geom_point(size = 5) +
  geom_point(data = df1, mapping = aes(x = Category, y = CategoryMetric), size = 5, color = "red")

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接