使用ggplot在一个堆积条形图中使用多个颜色标度

时间:2013-10-24 14:35:13

标签: r colors ggplot2 bar-chart

我创建了一个堆积条形图,描绘了市政当局在几年内(= x轴)的议会席位(= y轴)的分布情况。使用的代码和一些数据如下。不幸的是,我没有足够的积分来发布图表。

不同的政党也与一个名为“意识形态”的变量相关联,作为不同政治取向的一个类别(“进步”,“中等”,“保守”)。

我想以这样的方式修改颜色,例如保守党派有不同的蓝调;所有进步党派各种绿色;和所有温和​​派对,例如不同种类的红色;

意识形态上的变量位于同一数据帧(y)中。

任何提示如何进行此修改?我已经尝试过color = factor(意识形态)和group =意识形态,但无济于事。我也知道这个相关条目Using a pre-defined color palette in ggplot但是它与我的问题无关。

非常感谢。

使用过的命令:

    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

1 个答案:

答案 0 :(得分:9)

# 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

enter image description here

#####################################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)

enter image description here