R 如何可视化组和子组频率?
我必须使用组变量R 如何可视化组和子组频率?,r,dataframe,plot,ggplot2,R,Dataframe,Plot,Ggplot2,我必须使用组变量As和子组变量ADs绘制频率数据。可视化频率的最佳方法是什么,即饼图还是马赛克?ggplot2中是否有可用的功能 df <- data.frame(As=c('GeA','GeA','GeA', 'GA'), ADs=c('A44','A33','A37','A141'), freq=c(501,65,50,103)) # As ADs freq # 1 GeA A44 501 # 2 GeA A33
As
和子组变量ADs
绘制频率数据。可视化频率的最佳方法是什么,即饼图还是马赛克?ggplot2中是否有可用的功能
df <- data.frame(As=c('GeA','GeA','GeA', 'GA'),
ADs=c('A44','A33','A37','A141'),
freq=c(501,65,50,103))
# As ADs freq
# 1 GeA A44 501
# 2 GeA A33 65
# 3 GeA A37 50
# 4 GA A141 103
df堆叠条形图:
可以使用堆叠条形图:
library(ggplot2)
ggplot(data = df, aes(x = As, y = freq, fill = ADs)) +
geom_bar(stat = "identity")
可以添加此项并在绘图上获取标签:
p + geom_text(aes(label = paste(ADs, freq, sep=": ")),
position = position_stack(vjust = 0.5), size = 3) + #subgroups
stat_summary(fun.y = sum, aes(label = ..y.., group = As), geom = "text") + #groups
theme(legend.position="none")
下面两个答案与此相关
平铺图:
为此,我们需要调整数据:
df.2 <- df
df.2$ymax <- with(df.2, ave(freq, As, FUN=cumsum))
df.2 <- df.2[with(df.2, order(As)), ]
#for some reason lag function does not work properly in R 3.3.3
library(data.table)
setDT(df.2)[, ymin:=c(0,ymax[-.N])]
df.legend <- df.2[with(df.2, order(As)), ]
饼图:
堆叠条形图我没有清楚地了解如何使用堆叠条形图显示组和子组。你能粗略地画出来和大家分享吗?谢谢你的情节。很高兴看到每个子组的共享。请发布您正在使用的ggplot2的软件包版本,好吗?由于某些原因,我无法获得最后两个绘图的颜色。@请编辑您的问题。添加您得到的结果,以便可以重新打开它。我将尽快添加我的会话信息和包版本。我已经找到了无法获得相同输出的原因,这是由于ymin
值造成的。更改值(df.legend$ymin)后,否则在df.legend
上使用lag
功能将获得所需的输出!
df.2 <- df
df.2$ymax <- with(df.2, ave(freq, As, FUN=cumsum))
df.2 <- df.2[with(df.2, order(As)), ]
#for some reason lag function does not work properly in R 3.3.3
library(data.table)
setDT(df.2)[, ymin:=c(0,ymax[-.N])]
df.legend <- df.2[with(df.2, order(As)), ]
ggplot(df.2) +
geom_rect(aes(fill=As, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
geom_rect(aes(fill=ADs, ymax=ymax, ymin=ymin, xmax=3, xmin=0)) +
xlim(c(0, 4)) + theme(aspect.ratio=1) +
scale_x_continuous(breaks=c(1.5,3.5), labels=c("ADs", "As")) +
annotate("text", x=rep(1.5,4), y=c(50, 350,530,590),
label= paste(as.character(df.legend$ADs), df.legend$freq,sep= " = ")) +
annotate("text", x=rep(3.5,2), y=c(50, 350),
label= as.character(unique(df.legend$As))) +
theme(legend.position="none", axis.title.x=element_blank(),
axis.title.y=element_blank())
ggplot(df.2) +
geom_rect(aes(fill=As, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
geom_rect(aes(fill=ADs, ymax=ymax, ymin=ymin, xmax=3, xmin=0)) +
xlim(c(0, 4)) +
theme(aspect.ratio=1) +
coord_polar(theta="y") +
scale_x_continuous(breaks=c(0,3), labels=c("ADs", "As")) +
annotate("text", x=rep(1.5,4), y=c(50, 350,530,590),
label= as.character(df.legend$ADs)) +
annotate("text", x=rep(3.5,2), y=c(50, 350),
label= as.character(unique(df.legend$As))) +
theme(legend.position="none", axis.title.x=element_blank(),
axis.title.y=element_blank())