R. ggplot2。如何更改2行的颜色,以便在2-y轴图上区分它们

时间:2017-02-09 09:56:06

标签: r ggplot2

我是R编程的新手,并且在一段时间内一直在努力研究2-y轴图。最后,我几乎设法建立了一个客户问的聊天,但有一个例外:我的两行都是相同的颜色,不是我想要的。

我根据自己的需要调整了在互联网上找到的常用脚本。我唯一想知道的是如何制作不同颜色的线条而不是改变ggplot()函数,因为它产生了最终图形组合的图例(如果我们将线条设置为特定的颜色,那么“引导框” “对象不是任何一个图的grob的一部分,R返回错误)。

因此,我非常感谢有关该主题的帮助/想法,因为我想使用以下脚本来构建3-5行图并需要立即找到解决方案。

剧本:

library(ggplot2)
library(zoo)
library(gtable)
library(grid)

p4.1prod <-ggplot(data = p4_ch2_prod, aes (x = date, y = productivity, colour = productivity)) +
  #Производительность труда, 2013=100
  geom_line(size = 1)+
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_prod$date), to = max(p4_ch2_prod$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(85,105,5), expand = c(0,0), limits = c(85,105)) + #setting the domain of the scale

  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "black"),
        panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .2),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "#EDEDED", size = .2),
        panel.grid.minor = element_blank(),
        panel.background = element_rect(fill = "transparent", colour = NA),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1prod 


p4.1ret <- ggplot(data = p4_ch2_ret, aes (x = date, y=return, colour = "Отдача на капитал, % (правая ось)"))+
  geom_line(size = 1)+ #, colour = "#DDCC77"
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_ret$date), to = max(p4_ch2_ret$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(-15,30,5), expand = c(0,0), limits = c(-15,30)) +       
  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "black"),
        #panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .3),
        #panel.grid.minor.y = element_line(colour = "transparent", size = NA),
        #panel.grid.major.x = element_line(colour = "transparent", size = NA),
        #panel.grid.minor = element_line(colour = "transparent", size = NA),
        panel.background = element_rect(fill = NA),
        panel.grid = element_blank(),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        #axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1ret

g1 <- ggplot_gtable(ggplot_build(p4.1prod))
g2 <- ggplot_gtable(ggplot_build(p4.1ret))


pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,
                     pp$l, pp$b, pp$l)
# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)


leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]

g$grobs[[which(g$layout$name == "guide-box")]] <- 
                                  gtable:::cbind_gtable(leg1, leg2, "first")
grid.draw(g)


CairoPDF("plot4.pdf", width=5.23622, height=2.83465)
plot(g)
#plot(double_axis_graph(p4.1prod,p4.1ret))

dev.off()

数据

p4_ch2_prod =
    structure(list(date = structure(c(2010, 2010.25, 2010.5, 2010.75, 
2011, 2011.25, 2011.5, 2011.75, 2012, 2012.25, 2012.5, 2012.75, 
2013, 2013.25, 2013.5, 2013.75, 2014, 2014.25, 2014.5, 2014.75, 
2015, 2015.25, 2015.5, 2015.75, 2016, 2016.25, 2016.5), class = "yearqtr"), 
    productivity = c(86.367867684263, 88.3830463018648, 90.9947166315911, 
    93.0890082484875, 93.8358406567316, 95.415134362968, 95.1392324436027, 
    96.7490649309384, 97.2808331641485, 98.8920648452802, 98.6420849202174, 
    98.9827317138762, 100.118567582808, 99.3807124879942, 100.452579021256, 
    100.048140907942, 101.361645059966, 102.177365696465, 102.220265124015, 
    102.166598060618, 100.880500645703, 99.362767134256, 99.3229078598405, 
    98.7607969743729, 98.8417873432402, 99.153222798328, 98.2951748458741
    )), .Names = c("date", "productivity"), row.names = c(NA, 
27L), class = "data.frame")

p4_ch2_ret =
structure(list(date = structure(c(2010, 2010.25, 2010.5, 2010.75, 
2011, 2011.25, 2011.5, 2011.75, 2012, 2012.25, 2012.5, 2012.75, 
2013, 2013.25, 2013.5, 2013.75, 2014, 2014.25, 2014.5, 2014.75, 
2015, 2015.25, 2015.5, 2015.75, 2016, 2016.25, 2016.5), class = "yearqtr"), 
    return = c(11.7652500842395, 20.1068362958603, 24.4189393391774, 
    27.7603749135956, 22.6909560844267, 19.7512448106456, 9.65853487280893, 
    5.84667147280881, 4.23826276745065, 3.70105654292071, 5.21839712971448, 
    3.46196244414108, 6.08000307844456, -0.0813936964316113, 
    2.57919252646666, 0.206819314044496, 1.70263155186845, 5.21025899295173, 
    3.06177589390397, 4.16006634923697, -4.69833971033449, -10.8930467624443, 
    -11.4996955087892, -14.091528184568, -12.0277510178615, -7.46002412972934, 
    -11.475198069944)), .Names = c("date", "return"), row.names = c(NA, 
27L), class = "data.frame")

2 个答案:

答案 0 :(得分:2)

我不确定您希望实现的目标,但这是lattice的解决方案。我也对两个y轴进行了不同的着色,尽管没有必要。

library(lattice)
library(latticeExtra)


set.seed(1)
x = rnorm(10)
y1 = rnorm(10)
y2 = rnorm(10)

obj1 = xyplot(y1~x, type = c("p", "a"), ylab.right="")
obj2 = xyplot(y2~x,  type = c("p", "a"))
doubleYScale(obj1, obj2, text = c("y1", "y2"), 
             add.ylab2 = TRUE)

enter image description here

答案 1 :(得分:1)

scale_colour_identity()可能就是你想要的。我对代码进行了标记更改,并在行尾添加了# Here个注释。我也为y轴标签着色。如果不需要,请改回黑色。

此外,当您组合图例时,组合图例的中间有1 null个宽度,这会导致图例太间隔(在我看来)。将它们设置为零以获得更好的间距。

library(ggplot2)
library(zoo)
library(gtable)
library(grid)

p4.1prod <- ggplot(data = p4_ch2_prod, aes (x = date, y = productivity, colour = "blue")) +    # Here
  #Производительность труда, 2013=100
  geom_line(size = 1)+
  scale_colour_identity(guide = "legend", label = "Something blue") +   # Here
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_prod$date), to = max(p4_ch2_prod$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(85,105,5), expand = c(0,0), limits = c(85,105)) + #setting the domain of the scale

  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "blue"),   # Here
        panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .2),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "#EDEDED", size = .2),
        panel.grid.minor = element_blank(),
        panel.background = element_rect(fill = "transparent", colour = NA),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1prod 


p4.1ret <- ggplot(data = p4_ch2_ret, aes (x = date, y=return, colour = "red"))+  # Here
  geom_line(size = 1)+ #, colour = "#DDCC77"
  scale_colour_identity(guide = "legend", labels = c("Something red")) +  # Here
  labs(x=NULL, y=NULL)+
  scale_x_yearqtr(breaks = seq(from = min(p4_ch2_ret$date), to = max(p4_ch2_ret$date), by=0.25), format="Q%q %Y", expand=c(.01,0)) +
  scale_y_continuous(breaks = seq(-15,30,5), expand = c(0,0), limits = c(-15,30)) +       
  theme(axis.text.x = element_text(angle = 90, vjust = .5, size = 5, colour = "black"),
        axis.text.y = element_text(size = 5, colour = "red"),   # Here
        #panel.grid.major.y = element_line(colour = "#EDEDED", linetype = 2, size = .3),
        #panel.grid.minor.y = element_line(colour = "transparent", size = NA),
        #panel.grid.major.x = element_line(colour = "transparent", size = NA),
        #panel.grid.minor = element_line(colour = "transparent", size = NA),
        panel.background = element_rect(fill = NA),
        panel.grid = element_blank(),
        #text = element_text(family="Times New Roman"),
        axis.line.y = element_line(colour=NA), 
        #axis.line.x=element_line(colour="#ABABAB"),
        axis.ticks.length = unit(0,"cm"),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.spacing.x = unit(-.2,"cm"),
        legend.key = element_blank(),
        legend.key.height = unit(0, "cm"),
        legend.text = element_text(size = 5),
        legend.box.margin = unit (c(-3,1,1,1), "mm"),
        plot.margin = unit (c(1,0,0,0), "mm"))

p4.1ret

g1 <- ggplotGrob(p4.1prod)
g2 <- ggplotGrob(p4.1ret)


pp <- c(subset(g1$layout, name == "panel", se = t:r))
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,
                     pp$l, pp$b, pp$l)
# axis tweaks
ia <- which(g2$layout$name == "axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
# ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")   # Here - This line not needed 
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)


leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]

leg = gtable:::cbind_gtable(leg1, leg2, "first")              # Here
leg$widths[5:6] = unit(0, "cm")                               # Here

g$grobs[[which(g$layout$name == "guide-box")]] <- leg

grid.draw(g)