将两个散点图与不同的数据点组合在一起

Aka*_*ash 4 r ggplot2

我有一个要求,我想在同一个绘图区域中组合两个不同的散点图.一个散点图是度量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)
Run Code Online (Sandbox Code Playgroud)

所以基本上在综合结果之后,同一个图表中应该有4个圆圈,基本上我想在同一个图表中显示产品平均值和类别平均值,以便最终用户可以通过观察将产品平均值与avg类别进行比较图表.

此致,阿卡什

Tun*_*ung 5

你只需要您的数据转换widelong使用格式gathertidyr包.在这里阅读更多

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)
Run Code Online (Sandbox Code Playgroud)

编辑:根据产品数量动态更改颜色和图例时保持Category Ave颜色.redProduct

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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

reprex包(v0.2.0)于2018-03-31创建.