ggplot中的透明度变得白茫茫

问题描述 投票:1回答:1

我有这样的数据:

PENATVTY    educ    prop    order   alphayr
Vietnam         1   0.28109453  13  0.5
Vietnam         2   0.51243781  14  0.5
Vietnam         3   0.20646766  15  0.5
U.S. natives    1   0.28956793  16  0.1
U.S. natives    2   0.57418815  17  0.1
U.S. natives    3   0.13624393  18  0.1
All Immigrants  1   0.30822711  19  0.1
All Immigrants  2   0.42321587  20  0.1
All Immigrants  3   0.26855702  21  0.1
Germany         1   0.35264484  22  0.5
Germany         2   0.5768262   23  0.5
Germany         3   0.07052897  24  0.5
Philippines     1   0.40591398  25  0.5
Philippines     2   0.50672043  26  0.5
Philippines     3   0.08736559  27  0.5
Canada          1   0.4600639   28  0.5
Canada          2   0.46964856  29  0.5
Canada          3   0.07028754  30  0.5
China           1   0.48217054  31  0.5
China           2   0.35193798  32  0.5
China           3   0.16589147  33  0.5
India           1   0.82162162  34  0.5
India           2   0.13648649  35  0.5
India           3   0.04189189  36  0.5

我想让“美国本土人”和“所有移民”行透明化。无论我给alpha赋予哪个值,透明度都不会改变。我哪里做错了?我2周前开始写R,所以我的程序不容易阅读。谢谢。

 # create transperancy bars
      catsx$alphayr <- (ifelse(
      catsx$PENATVTY  == "U.S. natives"| 
      catsx$PENATVTY  == "All Immigrants", .5, 1))

  ggplot(catsx, 
   aes(x=reorder(PENATVTY, order), 
       y=prop, 
    fill=factor(educ, le`enter code here`vels = c("3", "2", "1")))) +
    geom_bar(stat="identity", position = "stack",
       aes(alpha=alphayr)) +
    coord_flip() +
    theme_bw() +
    ylab("Percent (%)") +
    xlab('') +
    theme(legend.position='none') +
    ggtitle('Exhibit 1') 
r ggplot2 alpha-transparency
1个回答
0
投票

正如here建议的那样,你应该将alphayr定义为factor以获得离散比例,然后使用scale_alpha_manual手动调整alpha比例。

ggplot(catsx, aes(x=reorder(PENATVTY, order), y=prop,
                  fill=factor(educ, levels=c("3","2","1")))) +
  geom_bar(stat="identity", position = "stack", aes(alpha=factor(alphayr))) +
  scale_alpha_manual(values = c("0.5"=0.5, "1"=1)) +
  coord_flip() + theme_bw() +
  ylab("Percent (%)") + xlab('') +
  theme(legend.position='none') + ggtitle('Exhibit 1') 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.