gpt4 book ai didi

r - 每个条形带有颜色渐变的堆叠条形图

转载 作者:行者123 更新时间:2023-12-02 04:14:14 27 4
gpt4 key购买 nike

我想为堆叠条形图着色,以便每个条形都有自己的父颜色,每个条形内的颜色是该父颜色的渐变。

示例:

这是一个最小的例子。我希望每个条形的颜色对于 color 是不同的,并且每个条形内的渐变由“clarity”设置。

library(ggplot2)

ggplot(diamonds, aes(color)) +
geom_bar(aes(fill = clarity), colour = "grey")

enter image description here

在我的实际问题中,每个组都有更多组:需要 18 个不同的条形和 39 种不同的渐变颜色。

最佳答案

我创建了一个函数ColourPalleteMulti,它可以让您根据数据中的子组创建多个调色板:

ColourPalleteMulti <- function(df, group, subgroup){

# Find how many colour categories to create and the number of colours in each
categories <- aggregate(as.formula(paste(subgroup, group, sep="~" )), df, function(x) length(unique(x)))
category.start <- (scales::hue_pal(l = 100)(nrow(categories))) # Set the top of the colour pallete
category.end <- (scales::hue_pal(l = 40)(nrow(categories))) # set the bottom

# Build Colour pallette
colours <- unlist(lapply(1:nrow(categories),
function(i){
colorRampPalette(colors = c(category.start[i], category.end[i]))(categories[i,2])}))
return(colours)
}

本质上,该函数会识别您有多少个不同的组,然后计算每个组中的颜色数量。然后它将所有不同的调色板连接在一起。

要使用调色板,最简单的方法是添加一个新列group,它将用于制作调色板的两个值粘贴在一起:

library(ggplot2)

# Create data
df <- diamonds
df$group <- paste0(df$color, "-", df$clarity, sep = "")

# Build the colour pallete
colours <-ColourPalleteMulti(df, "color", "clarity")

# Plot resultss
ggplot(df, aes(color)) +
geom_bar(aes(fill = group), colour = "grey") +
scale_fill_manual("Subject", values=colours, guide = "none")

enter image description here

<小时/>

编辑:

如果您希望每个条形图具有不同的颜色,您只需更改变量用于绘制条形图的方式即可:

# Plot resultss
ggplot(df, aes(cut)) +
geom_bar(aes(fill = group), colour = "grey") +
scale_fill_manual("Subject", values=colours, guide = "none")

enter image description here

<小时/>

A Note of Caution: In all honesty, the dataset you have want to plot probably has too many sub-categories within it for this to work.

Also, although this is visually very pleasing, I would suggest avoiding the use of a colour scale like this. It is more about making the plot look pretty, and the different colours are redundant as we already know which group the data is in from the X-axis.

关于r - 每个条形带有颜色渐变的堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49818271/

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