gpt4 book ai didi

r - 将调色板与 ggplot2 主题相关联

转载 作者:行者123 更新时间:2023-12-02 16:58:24 25 4
gpt4 key购买 nike

我希望我的 ggplot2 主题使用一组特定的颜色,但不知道如何避免在主题之外出现单独的行。

我有这些数据:

library(ggplot2)
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)

这是我绘制的虚拟主题:

mytheme <- theme(panel.grid.major = element_line(size = 2))

ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) +
mytheme

without custom colors

我希望点颜色默认为我的自定义调色板:

mycolors <- c("deeppink", "chartreuse", "midnightblue")

我可以以某种方式将其添加到我的 ggplot2 主题中,这样我就不会在最后不断重复这行额外的代码:

ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) +
mytheme +
scale_color_manual(values = mycolors)

with colors

我尝试过:

mytheme2 <- mytheme + scale_color_manual(values = mycolors)

但是得到了:

Error: Don't know how to add scale_color_manual(values = mycolors) to a theme object

最佳答案

您好,您可以将自定义元素放入列表中:

# Data
library("ggplot2")
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)

# Custom theme
mytheme <- theme(panel.grid.major = element_line(size = 2))
mycolors <- c("deeppink", "chartreuse", "midnightblue")
# put the elements in a list
mytheme2 <- list(mytheme, scale_color_manual(values = mycolors))

# plot
ggplot(mycars, aes(x = wt, y = mpg)) +
geom_point(aes(color = cyl)) +
mytheme2

关于r - 将调色板与 ggplot2 主题相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36476751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com