使用xkcd包和ggplot2:如何为条形图着色但是让人保持稳固?

时间:2014-04-17 16:16:05

标签: r colors ggplot2

我正在使用卓越的软件包进行值得关注的数据分析xkcd,但我对颜色有困难。我试图添加站在彩色geom_bar旁边的xkcd人,但我只能在条形图旁边做彩色geom_bar或男人,而不是两者。

library(xkcd)
library(ggplot2)
set.seed(16)

#borrowed from vignette
library(extrafont)
download.file("http://simonsoftware.se/other/xkcd.ttf", dest = "xkcd.ttf")
system("mkdir ~/.fonts")
system("cp xkcd.tff -t ~/.fonts")
library(extrafont)
font_import()
loadfonts()

#creates data from xkcd man: from vignette
mapping <- aes(
  x = x, y = y, scale = scale, ratioxy = ratioxy, angleofspine = angleofspine, 
  anglerighthumerus = anglerighthumerus, anglelefthumerus = anglelefthumerus,
  anglerightradius = anglerightradius, angleleftradius = angleleftradius,
  anglerightleg =  anglerightleg, angleleftleg = angleleftleg, 
  angleofneck = angleofneck, color = color)
dataman2 <- data.frame( 
  x= 3.5, y = 3, scale = 2, ratioxy = 0.5, angleofspine =  -pi/2, 
  anglerighthumerus = -pi/6, anglelefthumerus = 7*pi/6, 
  anglerightradius = 4*pi / 3, angleleftradius = 5*pi / 3, 
  angleleftleg = 4*pi / 3, anglerightleg = 5*pi / 3, 
  angleofneck = (3*pi/2) - (pi/10), color=c("red"))

#this rotates the xkcd man to match coord_flip
dataman2[ ,1:ncol(dataman2) %in% 5:(ncol(dataman2) - 1)] <- 
  dataman2[ ,c(5:(ncol(dataman2) -1))] - pi/2

#Create my df  
Ride <- data.frame(
  A = 1:6, 
  B = .01* seq(from = 5, to = 30, by= 5), 
  C = round(runif(6, min = .9, max = 1.1), 2) * c(2,1,2,2,1,2))

#These are the colors I want, but I want to add xkcd man on the right
ggplot(Ride, aes(A, C, fill = B)) + 
  geom_bar(stat="identity", width=.1) + coord_flip() + 
  scale_fill_continuous(low=c("#990000"), high=c("#009900")) #+ 

这些是我喜欢的颜色条。 color bars

#idea 1 - won't work b/c of fill = B
ggplot(Ride, aes(A, C, fill = B)) + 
  geom_bar(stat="identity", width=.1) + xkcdman(mapping,dataman2) 

#idea 2 - works but b&w; I am trying to add scale_fill_continuous (in comments)
ggplot() + xkcdrect(aes(xmin = A,
                        xmax = A + .25,
                        ymin = 0,
                        ymax = C),
                    Ride) + xkcdman(mapping,dataman2) + coord_flip() #+ 
  #scale_fill_continuous(low=c("#990000"), high=c("#009900"))

不幸的是,这些并不丰富多彩。 geom_bars + man

如何为条形图(连续)着色但是让人保持稳固? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:4)

这有效:

ggplot() + 
  xkcdrect(
    aes(xmin = A, xmax = A + .25, ymin = 0, ymax = C, fill = B),
    Ride
  ) + xkcdman(mapping,dataman2) + coord_flip() + 
  scale_fill_continuous(low=c("#990000"), high=c("#009900"))

enter image description here

只需将fill美学添加到aes