r堆叠条形图,颜色表示值 [英] r stacked bargraph with colors representing values

查看:321
本文介绍了r堆叠条形图,颜色表示值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用颜色表示来自单独数据列的颜色,并使用R 中的基本图形添加准确的颜色条。还有另一篇文章,但它是相当混乱,最后不帮我回答我的问题。

I'm looking to make a stacked barchart with colors representing values from a separate data column as well as add an accurate color bar using just the base graphics in R. There is one other post about this but it is pretty disorganized and in the end doesn't help me answer my question.

# create reproducible data
d <- read.csv(text='Day,Location,Length,Amount
            1,4,3,1.1
            1,3,1,.32
            1,2,3,2.3
            1,1,3,1.1
            2,0,0,0
            3,3,3,1.8
            3,2,1,3.54
            3,1,3,1.1',header=T)

# colors will be based on values in the Amount column
v1 <- d$Amount
# make some colors based on Amount - normalized
z <- v1/max(v1)*1000
colrs <- colorRampPalette(c('lightblue','blue','black'))(1000)[z]

# create a 2d table of the data needed for plotting
tab <- xtabs(Length ~ Location + Day, d)
# create a stacked bar plot
barplot(tab,col=colrs,space=0)

# create a color bar
plotr::color.bar

这样可以生成一个彩色编码的堆叠条形图,但颜色不能准确地表示数据。

This for sure produces a color coded stacked bar graph, but the colors do not represent the data accurately.

第1天,地点4和1的颜色应相同。另一个例子,Amount列中的第一个和最后一个条目是相同的,但是左侧列的顶部的颜色与右侧列的底部不匹配。

For Day 1, Locations 4 and 1 should be identical in color. Another example, the first and last entries in the Amount column are identical, but color of the top of the left column doesn't match the bottom of the right column.

此外,我发现如何在不同的帖子上创建一个颜色条,它使用 plotr :: color.bar 代码,但 plotr 显然不是一个包,我不知道如何继续。

Also, I found how to make a color bar on a different post and it uses the plotr::color.bar code, but plotr apparently isn't a package and I'm not sure how to carry on.

如何获得颜色以匹配相应的部分并添加一个准确的颜色条?

How can I get the colors to match the appropriate section and add an accurate color bar?

推荐答案

基于以下注释:

library(ggplot2)
ggplot(d, aes(x = Day, y = Length)) + geom_bar(aes(fill = Amount, order = Location), stat = "identity") 

这篇关于r堆叠条形图,颜色表示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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