您只需将数据从wide
to long
格式使用gather
来自tidyr
包裹。阅读更多here http://garrettgman.github.io/tidying/
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)
创建于 2018-03-31代表包 http://reprex.tidyverse.org(v0.2.0)。