将填充值填入ggplot2中的实际填充值 [英] Make the value of the fill the actual fill in ggplot2

查看:157
本文介绍了将填充值填入ggplot2中的实际填充值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让填充(标签)的价值变成填充本身?例如,在一个堆积条形图中,我有

  require(ggplot2)
big_votes_movies = movies [movies $ votes > 100000,]
p = ggplot(big_votes_movies,aes(x = rating,y = votes,fill = year))+ geom_bar(stat =identity)



1997年的价值和不是满足本身的价值?一个主题情节,如果你愿意?一个主题图的例子是:



如果这是可能的,我也可以在极坐标上绘制这些值,所以填充将成为值吗?

  p + coord_polar(theta =y)

解决方案

有一种方法可以做到这一点,但它有点难看。



当我第一次看它时,我想知道它是否可以使用geom_text来完成,但它虽然给出了一个表示,但它并不真正适合主题结构。这是第一次尝试:

  require(ggplot2)

big_votes_movies = movies [movies $ votes> ; 100000,]
p <-ggplot(big_votes_movies,aes(x = rating,y = votes,label = year))
p + geom_text(size = 12,aes(color = factor(year) (限制= c(8,9.5))+ scale_y_continuous(限制= c(90000,170000))
= 0.3))+ geom_jitter(alpha = 0)+
scale_x_continuous



然后我意识到你必须在grid / ggplot框架内实际渲染图像。你可以做到这一点,但你需要每年都有物理图像(我使用ggplot创建了基本图像,只使用一种工具,但也许Photoshop会更好!),然后制作自己的grobs,您可以添加自定义图像注释。然后您需要制作自己的直方图箱并使用apply进行绘图。见下文(它可以很容易地打扮起来)。可悲的是只适用于笛卡尔合作社:(b / b
$ b


pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $要求(网格)

年< -data.frame(year = unique(big_votes_movies $ year))
palette(rainbow(nrow(years)))
years $ col< -palette()#手动设置一些不同的颜色

#创建一个函数来写入年图像
writeYear< -function(year,col){

png(filename = paste(year,。png,sep =),width = 550,height = 300,bg =transparent)
im <-qplot(1,1,xlab = NULL ,ylab = NULL)+
theme(axis.text.x = element_blank(),axis.text.y = element_blank())+
theme(panel.background = element_rect(fill =transparent ,color = NA),plot.background = element_rect(fill =transparent,color = NA),panel.grid.minor = element_line(color =white))+
geom_text(label = year,size = 80,color = col)
print(im)
dev.off()

#创建占位符图像的函数
apply(years,1,FUN = function(x)writeYear(x [year],x [col]))

#然后汇总数据
summarydata< -big_votes_movies [,c(year,rating,votes)]
#make own bins(a cheat)
summarydata $ rating< -cut(summarydata $ rating,breaks = c(0,8,8.5,9,Inf),labels = c(0,8,8.5,9))
aggdata< - ddply(summarydata,c(year,rating),summarise,votes = sum(votes))
aggdata< -aggdata [order(aggdata $ rating),]
aggdata< -ddply( (评分),转换,ymax = cumsum(票),ymin = c(0,cumsum(票))[1:length(票)])
aggdata $ imgname< -apply(aggdata,1 ,FUN = function(x)paste(x [year],。png,sep =))

#工作出y轴上限
ymax< ; -max(aggdata $ ymax)

#绘制基本图表
z <-qplot(x = 10,y = 10,geom =blank)+ scale_x_continuous(limits = c (8,9.5))+ scale_y_continuous(limits = c(0,ymax))

#创建一个函数来创建grobs并调用annotat ion_custom函数
callgraph< -function(df){
tiles< -apply(df,1,FUN = function(x)return(annotation_custom(rasterGrob(image = readPNG(x [imgname])) ,
x = 0,y = 0,height = 1,width = 1,just = c(left,bottom)),
xmin = as.numeric(x [rating]] ),xmax = as.numeric(x [rating])+ 0.5,ymin = as.numeric(x [ymin]),ym ax = as.numeric(x [ymax]))))
return(tiles)
}

#然后将注释添加到图中
z + callgraph(aggdata)

以下是使用photoshopped图片的情节。我只是将它们保存在生成​​的图像上,然后运行脚本的后半部分以避免重新生成。

stack.imgur.com/h8mNV.pngalt =

确定 - 然后因为它困扰我,我决定安装extrafont和使用R构建更漂亮的图形: b
$ b



以下是代码:

  require(ggplot2)
require(png)
require(plyr)
require(grid)
require(extrafont)

#font_import(pattern =显示)运行此一次ONLY
#载入字体
载入字体(device =win)

#创建大数据的子集
big_votes_movies = movies [movies $ votes> ; 100000,]

#创建一个自定义调色板并附加到唯一年份(标签)表
年< -data.frame(year = unique(big_votes_movies $ year))
palette(rainbow(nrow(年)))
年$ col< -palette()

#function创建标签为png文件
writeYear< -function(年,col){

png(filename = paste(year,。png,sep =),width = 440,height = 190,bg =transparent)
im< -qplot(1,1,xlab = NULL,ylab = NULL,geom =blank)+
geom_text(label = year,size = 70,family =Showcard Gothic,color = col,alpha = 0.8)+
theme(axis.text.x = element_blank(),axis.text.y = element_blank())+
theme(panel.background = element_rect(fill =transparent,color = NA),
plot.background = element_rect(fill =transparent,color = NA),
panel.grid.minor = element_line(color =transparent),
面板。 grid.major = element_line(color =transparent),
axis.ticks = element_blank())
print(im)
dev.off()
}

#创建占位符图像的函数
apply( year,1,FUN = function(x)writeYear(x [year],x [col]))

#summarize数据并手动创建bin
summarydata< -big_votes_movies [,c(year,rating,votes)]
summarydata $ rating< -cut(summarydata $ rating,breaks = c(0,8,8.5,9,Inf),labels = c(0,8,8.5,9))

aggdata< - ddply(summarydata,c(year,rating),summarize,votes = sum(votes))
aggdata< -aggdata [order(aggdata $ rating),]
aggdata< -ddply(aggdata,。(rating),transform,ymax = cumsum(votes),ymin = c(0,cumsum(votes) )[1:length(票)])
#identify图像占位符
aggdata $ imgname< -apply(aggdata,1,FUN = function(x)paste(x [year],基本图
z <-qplot(x = 10,y = png,sep =))
ymax< -max(aggdata $ ymax)

# = 10,geom =空白,xlab =评分,ylab =投票\\\
,main =大电影票数\\\
)+
theme_bw()+
theme(panel.grid.major = element_line(color =transparent),
text = element_text(family =Kalinga,size = 20,face =bold)
)+
scale_x_continuous(limits = c(8,9.5))+
scale_y_continuous(limits = c(0,ymax))

#cre创建函数grobs和return annotation_custom()调用
callgraph< -function(df){
tiles< -apply(df,1,FUN = function(x)return(annotation_custom(rasterGrob(image = readPNG(x [imgname]),
x = 0,y = 0,height = 1,width = 1,just = c(left,bottom)),
xmin = as.numeric X [ 评级]),XMAX = as.numeric(X [ 评级])+ 0.5,YMIN = as.numeric(X [ YMIN]),YMAX = as.numeric(X [ YMAX] ))))
return(tiles)
}
#将图块添加到基本图表
z + callgraph(aggdata)


Is there a way to have the value of the fill (the label) become the fill itself? For instance, in a stacked bar plot, I have

require(ggplot2)
big_votes_movies = movies[movies$votes > 100000,]
p = ggplot(big_votes_movies, aes(x=rating, y=votes, fill=year)) + geom_bar(stat="identity")

Can the values of 1997 and whatnot be the fill itself? A motif plot, if you will? An example of a motif plot is:

If this is possible, can I also plot these values on polar coordinates, so the fill would become the value?

p + coord_polar(theta="y")

解决方案

There is a way to do it, but it's a little ugly.

When I first looked at it, I wondered if it could be done using geom_text, but although it gave a representation, it didn't really fit the motif structure. This was a first attempt:

require(ggplot2)

big_votes_movies = movies[movies$votes > 100000,]
p <- ggplot(big_votes_movies, aes(x=rating, y=votes, label=year))
p + geom_text(size=12, aes(colour=factor(year), alpha=0.3)) + geom_jitter(alpha=0) + 
  scale_x_continuous(limits=c(8, 9.5))   + scale_y_continuous(limits=c(90000,170000)) 

So then I realised you had to actually render the images within the grid/ggplot framework. You can do it, but you need to have physical images for each year (I created rudimentary images using ggplot, just to use only one tool, but maybe Photoshop would be better!) and then make your own grobs which you can add as custom annotations. You then need to make your own histogram bins and plot using apply. See below (it could be prettied up fairly easily). Sadly only works with cartesian co-ords :(

require(ggplot2)
require(png)
require(plyr)
require(grid)

years<-data.frame(year=unique(big_votes_movies$year))
palette(rainbow(nrow(years)))
years$col<-palette() # manually set some different colors

# create a function to write the "year" images
writeYear<-function(year,col){

  png(filename=paste(year,".png",sep=""),width=550,height=300,bg="transparent")
  im<-qplot(1,1,xlab=NULL,ylab=NULL) + 
    theme(axis.text.x = element_blank(),axis.text.y = element_blank()) +
    theme(panel.background = element_rect(fill = "transparent",colour = NA),     plot.background = element_rect(fill = "transparent",colour = NA), panel.grid.minor =     element_line(colour = "white")) +
    geom_text(label=year, size=80, color=col)
  print(im)
  dev.off()
}
#call the function to create the placeholder images
apply(years,1,FUN=function(x)writeYear(x["year"],x["col"]))

# then roll up the data
summarydata<-big_votes_movies[,c("year","rating","votes")]
# make own bins (a cheat)
summarydata$rating<-cut(summarydata$rating,breaks=c(0,8,8.5,9,Inf),labels=c(0,8,8.5,9))
aggdata <- ddply(summarydata, c("year", "rating"), summarise, votes  = sum(votes) )
aggdata<-aggdata[order(aggdata$rating),]
aggdata<-ddply(aggdata,.(rating),transform,ymax=cumsum(votes),ymin=c(0,cumsum(votes))[1:length(votes)])
aggdata$imgname<-apply(aggdata,1,FUN=function(x)paste(x["year"],".png",sep=""))

#work out the upper limit on the y axis
ymax<-max(aggdata$ymax)

#plot the basic chart
z<-qplot(x=10,y=10,geom="blank") + scale_x_continuous(limits=c(8,9.5)) + scale_y_continuous(limits=c(0,ymax))  

#make a function to create the grobs and call the annotation_custom function
callgraph<-function(df){
  tiles<-apply(df,1,FUN=function(x)return(annotation_custom(rasterGrob(image=readPNG(x["imgname"]),
                                                      x=0,y=0,height=1,width=1,just=c("left","bottom")),
                                                          xmin=as.numeric(x["rating"]),xmax=as.numeric(x["rating"])+0.5,ymin=as.numeric(x["ymin"]),ym    ax=as.numeric(x["ymax"]))))
      return(tiles)
    }

# then add the annotations to the plot
z+callgraph(aggdata)

and here's the plot with photoshopped images. I just save them over the generated imaages, and ran the second half of the script so as not to regenerate them.

OK - and then because it was bothering me, I decided to install extrafont and build the prettier graph using just R:

and here's the code:

  require(ggplot2)
  require(png)
  require(plyr)
  require(grid)
  require(extrafont)

  #font_import(pattern="Show") RUN THIS ONCE ONLY
  #load the fonts
  loadfonts(device="win")

  #create a subset of data with big votes
  big_votes_movies = movies[movies$votes > 100000,]

  #create a custom palette and append to a table of the unique years (labels) 
  years<-data.frame(year=unique(big_votes_movies$year))
  palette(rainbow(nrow(years)))
  years$col<-palette()

  #function to create the labels as png files
  writeYear<-function(year,col){

    png(filename=paste(year,".png",sep=""),width=440,height=190,bg="transparent")
    im<-qplot(1,1,xlab=NULL,ylab=NULL,geom="blank") + 
      geom_text(label=year,size=70, family="Showcard Gothic", color=col,alpha=0.8) +
      theme(axis.text.x = element_blank(),axis.text.y = element_blank()) +
      theme(panel.background = element_rect(fill = "transparent",colour = NA), 
            plot.background = element_rect(fill = "transparent",colour = NA), 
            panel.grid.minor = element_line(colour = "transparent"), 
            panel.grid.major = element_line(colour = "transparent"),
            axis.ticks=element_blank())
    print(im)
    dev.off()
  }

  #call the function to create the placeholder images
  apply(years,1,FUN=function(x)writeYear(x["year"],x["col"]))

  #summarize the data, and create bins manually
  summarydata<-big_votes_movies[,c("year","rating","votes")]
  summarydata$rating<-cut(summarydata$rating,breaks=c(0,8,8.5,9,Inf),labels=c(0,8,8.5,9))

  aggdata <- ddply(summarydata, c("year", "rating"), summarise, votes  = sum(votes) )
  aggdata<-aggdata[order(aggdata$rating),]
  aggdata<-ddply(aggdata,.(rating),transform,ymax=cumsum(votes),ymin=c(0,cumsum(votes))[1:length(votes)])
  #identify the image placeholders
  aggdata$imgname<-apply(aggdata,1,FUN=function(x)paste(x["year"],".png",sep=""))
  ymax<-max(aggdata$ymax)

  #do the basic plot
  z<-qplot(x=10,y=10,geom="blank",xlab="Rating",ylab="Votes \n",main="Big Movie Votes \n") + 
    theme_bw() +
    theme(panel.grid.major = element_line(colour = "transparent"),
          text = element_text(family="Kalinga", size=20,face="bold")        
          ) +
    scale_x_continuous(limits=c(8,9.5)) + 
    scale_y_continuous(limits=c(0,ymax))  

  #creat a function to create the grobs and return annotation_custom() calls
  callgraph<-function(df){
    tiles<-apply(df,1,FUN=function(x)return(annotation_custom(rasterGrob(image=readPNG(x["imgname"]),
                                                        x=0,y=0,height=1,width=1,just=c("left","bottom")),
                                                 xmin=as.numeric(x["rating"]),xmax=as.numeric(x["rating"])+0.5,ymin=as.numeric(x["ymin"]),ymax=as.numeric(x["ymax"]))))
    return(tiles)
  }
  #add the tiles to the base chart
  z+callgraph(aggdata)

这篇关于将填充值填入ggplot2中的实际填充值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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