单个栏上的ggplot透明度 [英] ggplot transparency on individual bar

查看:166
本文介绍了单个栏上的ggplot透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正尝试使用ggplot创建一个条形图,其中有一个部分透明的条形图。

I am currently attempting to use ggplot to create a bar chart with a single bar that is partially transparent.

我有以下代码:

I have the following code:

dt1 <- data.table(yr=c(2010,2010,2011,2011),
                  val=c(1500,3000,2000,1100),
                  x=c("a","b","a","b"))


ggplot() + geom_bar(data=dt1, aes(x=yr, y=val,fill=x),stat="identity") +
  scale_x_continuous(breaks=dt1$yr)

这将创建一个简单的图表,其中2具有堆叠数据的列。我已经尝试了下面的代码来调整2011年的价值以获得透明度,但是我没有多少运气。任何指针?

This will create a simple chart with 2 columns with stacked data. I have tried the following code to adjust the 2011 value to have transparency, however I am not having much luck. Any pointers?

dt1[,alphayr:=ifelse(yr==2011,.5,1)]
ggplot() + geom_bar(data=dt1, aes(x=yr, y=val,fill=x),stat="identity", alpha=dt1$alphayr) +
scale_x_continuous(breaks=dt1$yr)


推荐答案

首先,将 alpha 在@jazzurro建议的 aes 内。但是,您应该使用因子来获得离散比例。然后你可以手动调整alpha比例。

First you put the alpha inside the aes as suggested by @jazzurro. However, you should use factor for this to get a discrete scale. Then you can manually adjust the alpha scale.

ggplot() + geom_bar(data=dt1, aes(x=yr, y=val, fill=x, alpha=factor(alphayr)), stat="identity") +
  scale_x_continuous(breaks=dt1$yr) +
  scale_alpha_manual(values = c("0.5"=0.5, "1"=1), guide='none')

这篇关于单个栏上的ggplot透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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