更改堆叠条形图的颜色,但保持每个类的堆叠顺序递增

如何解决更改堆叠条形图的颜色,但保持每个类的堆叠顺序递增

我一直在尝试创建一个堆积的条形图,该图的颜色与地图中的颜色有关。基本上,我具有给定多边形覆盖的面积比例。我已经预先对 df 进行了排序,因此每个Proportion的堆栈Class的降序排列。如果将fill的值设置为一个连续变量,即Cluster(但是我不能更改堆栈的特定颜色),并且将它们转换为因子Clu,则堆栈的顺序丢失了,或者我可以设法对它们进行排序,但是对于整个图形,不是每个类...相同的Cluster可以出现在不同的类中,即集群 Two

          Num    Class Cluster Proportion   Clu Order consec
1    9  Class_9       2      0.859   Two     1      1
2    9  Class_9       5      0.141  Five     2      2
3   10 Class_10       2      0.622   Two     1      3
4   10 Class_10       1      0.179   One     2      4
5   10 Class_10       7      0.165 Seven     3      5
6   10 Class_10       6      0.034   Six     4      6
7   11 Class_11       7      1.000 Seven     1      7
8   12 Class_12       2      0.571   Two     1      8
9   12 Class_12       8      0.289 Eight     2      9
10  12 Class_12       1      0.140   One     3     10
11  13 Class_13       8      0.581 Eight     1     11
12  13 Class_13       4      0.210  Four     2     12
13  13 Class_13       2      0.112   Two     3     13
14  13 Class_13       3      0.079 Three     4     14
15  13 Class_13       5      0.018  Five     5     15

我已经设法在代码上走了这么远。

cols<-c(One='Blue',Two='Red',Three='Yellow',Four='lightblue',Five='darkgrey',Six='Black',Seven='cyan',Eight='Green')
  

ggplot(Tx,aes(x=Class,y=Proportion,fill= Clu)) + 
  geom_col(width = .7,colour="black",lwd=0.1) +
  geom_text(aes(label=ifelse(Proportion >= 0.05,sprintf("%.2f",Proportion),"")),position=position_stack(vjust=0.5),colour="white") +
  coord_flip() +
  scale_y_continuous(labels = function(y) paste0(y))+
  scale_fill_manual(values = cols)+ 
  labs(y="",x="")

总而言之,我想为每个类创建一个图,其中比例按升序排列,但要为每个聚类指定颜色

enter image description here

解决方法

一种选择(与您的想法有所不同)是使用position.dodgetidytext::reorder_within

library(tidyverse)
library(tidytext)

cols<-c('Blue','Red','Yellow','lightblue','darkgrey','Black','cyan','Green')

Tx %>%
  mutate(Cluster2 = reorder_within(Cluster,Proportion,Class)) %>%
  ggplot(aes(Cluster2,fill = as.factor(Cluster))) +
  geom_col(position = position_dodge2(preserve = "single")) +
  scale_x_reordered() +
  scale_fill_manual(values = cols) +
  coord_flip() +
  facet_grid(Class~.,scales = 'free_y',space = 'free')

enter image description here


如果您确实需要具有不同顺序的堆叠条形图,则另一个选择是分别为每个类生成图(这允许正确的顺序),然​​后将它们重新堆叠在一起。可以使用cowplot::plot_gridcowplot::get_legend来完成。

以正确的顺序生成地块列表,并将其堆叠到一个地块中。

library(tidyverse)
library(cowplot)

Tx2 <- Tx %>%
  mutate(Cluster = factor(Cluster))

cols<-c(One='Blue',Two='Red',Three='Yellow',Four='lightblue',Five='darkgrey',Six='Black',Seven='cyan',Eight='Green')


p_list <- lapply(unique(Tx2$Class),function(x){
  p <-  Tx2 %>%
    filter(Class == x) %>%
    ggplot(aes(Class,fill = reorder(Clu,-Proportion))) +
    geom_col(color = 'black') +
    geom_text(aes(label=ifelse(Proportion >= 0.05,sprintf("%.2f",Proportion),"")),position=position_stack(vjust=0.5),color = 'white') +
    coord_flip() +
    scale_fill_manual(values = cols) +
    labs(x = NULL,y = NULL) +
    theme_minimal() +
    theme(legend.position = 'none') 
  
 if (x != 'Class_13') p <- p + theme(axis.text.x = element_blank()) 
  
 p
})



p_col <- plot_grid(plotlist = p_list,ncol = 1,align = 'v',rel_heights = c(rep(1,4),1.2))

生成要使用的图例。

p <- ggplot(Tx2,aes(Class,as.numeric(Cluster)))) +  
  geom_col(color = 'black') +
  scale_fill_manual(values = cols,labels= 1:8,name = 'Cluster')
l <- cowplot::get_legend(p)

将堆积的图和图例放在一起。

plot_grid(p_col,l,rel_widths = c(3,.4))

!enter image description here


数据

Tx <- read.table(text = 
'  Num    Class Cluster Proportion   Clu Order consec
1    9  Class_9       2      0.859   Two     1      1
2    9  Class_9       5      0.141  Five     2      2
3   10 Class_10       2      0.622   Two     1      3
4   10 Class_10       1      0.179   One     2      4
5   10 Class_10       7      0.165 Seven     3      5
6   10 Class_10       6      0.034   Six     4      6
7   11 Class_11       7      1.000 Seven     1      7
8   12 Class_12       2      0.571   Two     1      8
9   12 Class_12       8      0.289 Eight     2      9
10  12 Class_12       1      0.140   One     3     10
11  13 Class_13       8      0.581 Eight     1     11
12  13 Class_13       4      0.210  Four     2     12
13  13 Class_13       2      0.112   Two     3     13
14  13 Class_13       3      0.079 Three     4     14
15  13 Class_13       5      0.018  Five     5     15')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-