在条形图下显示值表 [英] Show the table of values under the bar plot
问题描述
我问这个没有找到可以尝试的东西,因为我没有找到相同的东西.我为此表示歉意.
I ask this without find something to try, because I didn't find something same. I apologize for this.
来自此条形图:
df <- structure(list(year = 2002:2005, work = c(1L, 2L, 3L, 2L), confid = c(8L,
5L, 0L, 6L), jrs = c(0L, 3L, 4L, 5L)), .Names = c("year", "work",
"confid", "jrs"), class = "data.frame", row.names = c(NA, -4L
))
library(ggplot2)
library(reshape)
md <- melt(df, id=(c("year")))
temp.plot <- ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
geom_bar(stat="identity")+
theme(axis.text.x=element_text(angle=90))+
ggtitle("Score Distribtion")
temp.plot
我想问问是否有任何简单的方法可以使用ggplot2来获取每年的值,因为它在每个变量的barplot中. 这里是一个虚拟示例输出:
I would like to ask if is there any simple way using ggplot2 to have the value under every year as it is in barplot for every variable. Here a dummy example output:
推荐答案
最好在每个小节内绘制计数.例如:
It might be better to plot the counts within each bar. For example:
library(ggplot2)
theme_set(theme_classic())
ggplot(data=md, aes(x=year, y=value, fill=variable)) +
geom_bar(stat="identity") +
ggtitle("Score Distribution") +
geom_text(aes(label=value), position=position_stack(vjust=0.5), colour="white") +
labs(fill="")
如果您仍想在图表下方使用表格,我不知道有什么简单的方法,但是您可以为表格创建单独的tableGrob
,将图例提取为单独的grob(图形对象),然后放置分别取出每个部分.对各个部分进行布局需要手动进行一些调整,尽管比我更了解网格图形的人也许可以实现这一点的自动化.这是一个示例:
If you still want a table beneath the plot, I don't know of a simple way, but you can create a separate tableGrob
for the table, extract the legend as a separate grob (graphical object), then lay out each part separately. Laying out the various parts requires some tweaking by hand, although someone who understands grid graphics better than I do might be able to automate that. Here's an example:
library(grid)
library(gridExtra)
# Function to extract legend
# https://stackoverflow.com/a/13650878/496488
g_legend <- function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
p = ggplot(data=md, aes(x=year, y=value, fill=variable) ) +
geom_bar(stat="identity")+
#theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=0.5))+
ggtitle("Score Distribution") +
labs(fill="")
# Extract the legend as a separate grob
leg = g_legend(p)
# Create a table grob
tab = t(df)
tab = tableGrob(tab, rows=NULL)
tab$widths <- unit(rep(1/ncol(tab), ncol(tab)), "npc")
# Lay out plot, legend, and table grob
grid.arrange(arrangeGrob(nullGrob(),
p + guides(fill=FALSE) +
theme(axis.text.x=element_blank(),
axis.title.x=element_blank(),
axis.ticks.x=element_blank()),
widths=c(1,8)),
arrangeGrob(arrangeGrob(nullGrob(),leg,heights=c(1,10)),
tab, nullGrob(), widths=c(6,20,1)),
heights=c(4,1))
这篇关于在条形图下显示值表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!