您只需使用tidyr 包中的gather 将数据从wide 转换为long 格式。阅读更多here
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 的颜色保留在red 中,同时根据产品数量动态更改每个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)
由reprex package (v0.2.0) 于 2018 年 3 月 31 日创建。