将调色板与ggplot2主题相关联 [英] Associate a color palette with ggplot2 theme

查看:129
本文介绍了将调色板与ggplot2主题相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的ggplot2主题使用一组特定的颜色,但没有看到如何避免主题外的单独行。



我有这个data:

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

这里是一个虚拟的主题: b
$ b

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

ggplot(mycars, aes(color = cyl))+
mytheme



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

  mycolors< -c(deeppink,chartreuse,midnightblue)

我能以某种方式将其添加到我的ggplot2主题中,以便我不会不断重复此操作

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

$ b $ p












$ b $ p> mytheme2< - mytheme + scale_color_manual(values = mycolors)

但是得到:
$ b


错误:不知道如何将scale_color_manual(values = mycolors)添加到
a主题对象



你好你可以把你的自定义元素放在列表中

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

#自定义主题
mytheme< - theme(panel.grid.major = element_line(大小= 2))
mycolors< - c(deeppink,chartreuse,midnightblue)
#将元素放入列表
mytheme2< - list(mytheme, scale_color_manual(values = mycolors))

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


I want my ggplot2 theme to use a specific set of colors, but don't see how to avoid a separate line outside of the theme.

I have this data:

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

And here's a dummy theme I plot with:

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

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

I want the point colors to default to my custom palette:

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

Can I somehow add that to my ggplot2 theme so that I don't constantly repeat this extra line of code at the end:

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

I tried:

mytheme2 <- mytheme + scale_color_manual(values = mycolors)

But got:

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

解决方案

Hi you can put your custom element in a list :

# 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

这篇关于将调色板与ggplot2主题相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆