使用ggplot在一个堆叠条形图中的多个色阶 [英] Multiple colour scales in one stacked bar plot using ggplot

查看:21
本文介绍了使用ggplot在一个堆叠条形图中的多个色阶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个堆叠条形图,它描绘了几年来(= x 轴)在一个自治市内的政党之间的议会席位分布(= y 轴).使用的代码和一些数据如下.不幸的是,我还没有足够的点数来发布图表.

I created a stacked bar plot which depicts the distribution of council seats (= y-axis) among parties within a municipality over several years (= x-axis). The used code and some data is below. Unfortunately, I don't have yet sufficient points to post the graph.

不同的政党还与一个称为意识形态"的变量相关联,作为不同政治倾向(进步"、温和"、保守")的类别.

The different parties are also associated with a variable called "ideology" as a category for different political orientations ("progressive", "moderate", "conservative").

我想以这样的方式修改颜色,例如保守党有不同类型的忧郁;所有进步党派不同种类的绿色;以及所有温和派,例如不同种类的红色;

I would like to modify the colors in such a way that all e.g. conservative parties have different kinds of blues; all progressive parties different kinds of green; and all moderate parties e.g. different kinds of red;

意识形态上的变量在同一个数据框 (y) 中.

The variable on the ideology is in the same dataframe (y).

任何提示如何获得此修改?我已经尝试过 color=factor(ideology) 和 group=ideology 但无济于事.我也知道这个相关条目 在 ggplot 中使用预定义的调色板 但是它没有与我的问题无关.

Any hint how to get this modification? I already tried color=factor(ideology) and group=ideology but to no avail. I am also aware of this related entry Using a pre-defined color palette in ggplot however it doesn't pertain specifically to my problem.

非常感谢.

使用的命令:

    municipality.plot <- ggplot(y, aes(x=as.factor(year), y=seats, fill=party, color=party)) +
      geom_bar(bandwidth=1, stat="identity", group="party", position="fill") +
      labs(x="year", y="% of seats for municipality")

示例数据:

   year district.id                                                         party seats ideology
1  2012         127                  Stranka Pravde I Razvoja Bosne I Hercegovine     1        p
2  2012         127                                Savez Za Bolju Buducnost (SBB)     3        p
3  2008         127                              Stranka Demokratske Akcije (SDA)    13        p
4  2004         127                              Stranka Demokratske Akcije (SDA)    14        p
5  2008         127                          Hrvatska Demokratska Zajednica (HDZ)     1        c
6  2008         127                  Stranka Pravde I Razvoja Bosne I Hercegovine     1        p
7  2012         127                        Stranka Za Bosnu I Hercegovinu (SzBiH)     4        p
8  2000         127                              Socijaldemokratska Partija (SDP)     8        m
9  2012         127                     Narodna Stranka Radom Za Boljitak (NSRzB)     2        m
10 2012         127                            Socijaldemokratska Unija Bih (SDU)     1        p
11 2000         127                                         Koalicija - SDA, SBiH    15        p
12 2008         127                              Socijaldemokratska Partija (SDP)     5        m
13 2008         127                     Narodna Stranka Radom Za Boljitak (NSRzB)     1        m
14 2008         127                                          Koalicija - LDS, SDU     2        m
15 2000         127 Lgk-liberalno-gradanska Koalicija Bih (liberali Bih, Gds Bih)     1        m
16 2000         127                               Nova Hrvatska Inicijativa (NHI)     1        c
17 1997         127                              Socijaldemokratska Partija (SDP)     3        m
18 2012         127                              Socijaldemokratska Partija (SDP)     6        m
19 2004         127                        Stranka Za Bosnu I Hercegovinu (SzBiH)     5        p
20 1997         127                 Bosanskohercegovacka Patriotska Stranka (BPS)     9        p
21 2000         127                 Bosanskohercegovacka Patriotska Stranka (BPS)     3        p
22 2008         127                        Stranka Za Bosnu I Hercegovinu (SzBiH)     4        p
23 1997         127                          Hrvatska Demokratska Zajednica (HDZ)     5        c
24 2000         127                          Hrvatska Demokratska Zajednica (HDZ)     2        c
25 2012         127                              Stranka Demokratske Akcije (SDA)    10        p
26 2004         127                              Socijaldemokratska Partija (SDP)     6        m
27 1997         127                          Koalicija - SDA, SBiH, Liberali, GDS    13        p

推荐答案

# load relevant packages
library(scales)
library(grid)
library(ggplot2)
library(plyr)

# assume your data is called df
# order data by year, ideology and party
df2 <- arrange(df, year, ideology, party)

########################################


# create one colour palette per ideology

# count number of parties per ideology
tt <- with(df2[!duplicated(df2$party), ], table(ideology))

# conservative parties blues
# progressive parties green
# moderate parties red    
blue <- brewer_pal(pal = "Blues")(tt[names(tt) == "c"])
green <- brewer_pal(pal = "Greens")(tt[names(tt) == "p"])
red <- brewer_pal(pal = "Reds")(tt[names(tt) == "m"])

# create data on party and ideology
party_df <- df2[!duplicated(df2$party), c("party", "ideology")]

# set levels of ideologies; c, p, m
party_df$ideology <- factor(party_df$ideology, levels = c("c", "p", "m"))

# order by ideology and party
party_df <- arrange(party_df, ideology, party)

# add fill colours
party_df$fill <- c(blue, green, red)

# set levels of parties based on the order of parties in party_df
party_df$party <- factor(party_df$party, levels = party_df$party)

# use same factor levels for parties in df2
df2$party <- factor(df2$party, levels = party_df$party)

##################################


# Alternative 1. Plot with one legend

g1 <- ggplot(data = df2, aes(x = as.factor(year),
                       y = seats,
                       fill = party)) +
  geom_bar(stat = "identity", position = "fill") +
  labs(x = "year", y = "% of seats for municipality") +
  coord_cartesian(ylim = c(0, 1)) +
  scale_fill_manual(values = party_df$fill, name = "Parties") +
  theme_classic()
g1

#####################################3
# alt 2. Plot with separate legends for each ideology


# create separate plots for each ideology to get legends

# conservative parties blue
cons <- ggplot(data = df2[df2$ideology == "c", ],
               aes(x = as.factor(year),
                   y = seats,
                   fill = party)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_fill_manual(values = blue, name = "Conservative parties" )


# extract 'cons' legend
tmp <- ggplot_gtable(ggplot_build(cons))
leg <- which(sapply(tmp$grobs, function(x) x$name) ==  "guide-box")
legend_cons <- tmp$grobs[[leg]]


# progressive parties green
prog <- ggplot(data = df2[df2$ideology == "p", ],
               aes(x = as.factor(year),
                   y = seats,
                   fill = party)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_fill_manual(values = green, name = "Progressive parties" )

# extract 'prog' legend
tmp <- ggplot_gtable(ggplot_build(prog))
leg <- which(sapply(tmp$grobs, function(x) x$name) ==  "guide-box")
legend_prog <- tmp$grobs[[leg]]


# moderate parties red
mod <- ggplot(data = df2[df2$ideology == "m", ],
              aes(x = as.factor(year),
                  y = seats,
                  fill = party)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_fill_manual(values = red, name = "Moderate parties" )


# extract 'mod' legend
tmp <- ggplot_gtable(ggplot_build(mod))
leg <- which(sapply(tmp$grobs, function(x) x$name) ==  "guide-box")
legend_mod <- tmp$grobs[[leg]]

#######################################


# arrange plot and legends

# define plotting regions (viewports) for plot and legends
vp_plot <- viewport(x = 0.25, y = 0.5,
                    width = 0.5, height = 1)

vp_legend_cons <- viewport(x = 0.66, y = 0.87,
                           width = 0.5, height = 0.15)

vp_legend_prog <- viewport(x = 0.7, y = 0.55,
                           width = 0.5, height = 0.60)

vp_legend_mod <- viewport(x = 0.75, y = 0.2,
                          width = 0.5, height = 0.30)

# clear current device
grid.newpage()

# add objects to the viewports
# plot without legend
print(g1 + theme(legend.position = "none"), vp = vp_plot)
upViewport(0)

# legends
pushViewport(vp_legend_cons)
grid.draw(legend_cons)
upViewport(0)

pushViewport(vp_legend_prog)
grid.draw(legend_prog)  
upViewport(0)

pushViewport(vp_legend_mod)
grid.draw(legend_mod)

这篇关于使用ggplot在一个堆叠条形图中的多个色阶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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