在GGPLOT2中,美国有可能定义定义的调色板吗?

发布于 2025-01-23 08:15:36 字数 1126 浏览 2 评论 0原文

我想在用GGPLOT2绘制图形时使用自定义的调色板。我只是以Viridis制作的一个例子:

library(ggplot2)
library(viridis)

ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() + coord_fixed() +
  scale_fill_viridis() + theme_bw()

我的想法是使用以下调色板:

palette <- c("#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B", 
              "#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000")

library(scales)
show_col(palette)

”在此处输入图像描述

我应该使用scale> scale> scale_colour_manual(values = palette)> t我定义的一个。我在做某种错误吗?

library(ggplot2)
ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() + coord_fixed() +
  scale_colour_manual(values = palette) + theme_bw()

I would like to use a custom defined palette in drawing a graph with ggplot2. I take just an example made with viridis:

library(ggplot2)
library(viridis)

ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() + coord_fixed() +
  scale_fill_viridis() + theme_bw()

My idea is to use the following palette:

palette <- c("#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B", 
              "#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000")

library(scales)
show_col(palette)

enter image description here

I supposed to use scale_colour_manual(values = palette) but it looks like it doesn't take my custom-defined one. I am doing some kind of mistake?

library(ggplot2)
ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() + coord_fixed() +
  scale_colour_manual(values = palette) + theme_bw()

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若水微香 2025-01-30 08:15:36

问题在于您使用的是scale_color_manual,它仅适用于映射在color aes上的离散变量。由于您有一个连续变量,该变量在fill aes上映射到一个选项是使用scale_fill_gradientn

set.seed(123)

library(ggplot2)

palette <- c(
  "#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B",
  "#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000"
)

ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() +
  coord_fixed() +
  scale_fill_gradientn(colors = palette)

“”

The issue is that you are using scale_color_manual which will only work for discrete variables mapped on the color aes. As you have a continuous variable which is mapped on the fill aes one option would be to use scale_fill_gradientn:

set.seed(123)

library(ggplot2)

palette <- c(
  "#771C19", "#AA3929", "#E25033", "#F27314", "#F8A31B",
  "#E2C59F", "#B6C5CC", "#8E9CA3", "#556670", "#000000"
)

ggplot(data.frame(x = rnorm(10000), y = rnorm(10000)), aes(x = x, y = y)) +
  geom_hex() +
  coord_fixed() +
  scale_fill_gradientn(colors = palette)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文