如何在ggplot2中改变线的颜色(附实例)

538 阅读1分钟

你可以使用以下基本语法在ggplot2中指定线条颜色。

ggplot(df, aes(x=x, y=y, group=group_var, color=group_var)) + 
    geom_line() +
    scale_color_manual(values=c('color1', 'color2', 'color3'))

下面的例子展示了如何在实践中使用这种语法。

例子:在ggplot2中改变线条颜色

假设我们在R中拥有以下数据框。

#create data frame
df <- data.frame(store=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
                 week=c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                 sales=c(9, 12, 15, 7, 9, 14, 10, 16, 19))

#view data frame
df

  store week sales
1     A    1     9
2     A    2    12
3     A    3    15
4     B    1     7
5     B    2     9
6     B    3    14
7     C    1    10
8     C    2    16
9     C    3    19

现在假设我们在ggplot2中创建以下线段图,以可视化地显示按周和按商店划分的总销售额。

library(ggplot2)

#create line plot
ggplot(df, aes(x=week, y=sales, group=store, color=store)) + 
    geom_line(size=2)

默认情况下,ggplot2使用默认的红色、绿色和蓝色的调色板来绘制线条。

然而,你可以使用**scale_color_manual()**函数来为线条指定你自己的颜色。

library(ggplot2)

#create line plot
ggplot(df, aes(x=week, y=sales, group=store, color=store)) + 
    geom_line(size=2) +
    scale_color_manual(values=c('orange', 'pink', 'red'))

现在的颜色是橙色、粉色和红色。

请注意,你也可以使用十六进制颜色代码来指定颜色。

library(ggplot2)

#create line plot
ggplot(df, aes(x=week, y=sales, group=store, color=store)) + 
    geom_line(size=2) +
    scale_color_manual(values=c('#063970', '#A69943', '#7843a6'))

现在的颜色与我们选择的特定十六进制颜色代码相对应。

其他资源

下面的教程解释了如何在ggplot2中执行其他常见任务:

如何在ggplot2中旋转轴标签
如何在ggplot2中改变点的大小
如何在ggplot2图中添加文本