【问题标题】:Is there a way to manually set order of bar plot in R ggplot2? [duplicate]有没有办法在 R ggplot2 中手动设置条形图的顺序? [复制]
【发布时间】:2022-08-24 08:21:50
【问题描述】:

我正在为一个组织做一些数据分析,我正在尝试更改条形图中条形的顺序。现在,它是按字母顺序排列的,但我想将它设置为一周中的天数。我曾尝试使用级别和因子,但我认为它可能不起作用,因为我正在从 excel 文件中读取数据,并且每一列都是当天所有值的总和。有没有办法通过 ggplot2 做到这一点而无需编辑原始的 excel 文件?

enter image description here

  • 有序因子是执行此操作的标准方法,该站点上有很多答案演示了如何执行此操作。如果您查看这些内容并且可以共享一些不起作用的特定代码,将会更容易提供帮助。
  • 这个想法是ggplot(df, aes(factor(x = day_of_week))) + geom_bar() + scale_x_discrete(limits=c(\'Mon\', \'Tue\', \'Wed\', \'Thu\', \'Fri\', \'Sat\', \'Sun\')) 但是发布你的代码会有所帮助
  • 请参阅较新链接的重复问题中的答案。

标签: r ggplot2


【解决方案1】:

基本上做类似ggplot(df,aes(x=factor(V1,level=unique(V1)),y=V3,fill=V2))的事情(或添加fct_rev来颠倒顺序):

t=read.table("https://pastebin.com/raw/GyEiXxNs",r=1)
t=t[,c(4,1,3,2)]
colnames(t)=paste0("V",1:ncol(t)) # prevent ggplot from reordering the bars for each column
t=t[order(as.matrix(t)%*%(1:ncol(t))^2),] # reorder rows so that rows with a high percentage of the first column are placed first

w2l=function(x)data.frame(V1=rownames(x)[row(x)],V2=colnames(x)[col(x)],V3=unname(c(unlist(x))))
t2=w2l(t) # wide to long

lab=round(100*t2$V3)
lab[lab<=1]="" # don't display labels for 0% or 1%

ggplot(t2,aes(x=fct_rev(factor(V1,levels=unique(V1))),y=V3,fill=V2))+
geom_bar(stat="identity",width=1,position=position_fill(reverse=T),size=.1,color="gray10")+
geom_text(aes(label=lab),position=position_stack(vjust=.5,reverse=T),size=3.5)+
coord_flip()+
scale_x_discrete(expand=c(0,0))+
scale_y_discrete(expand=c(0,0))+
scale_fill_manual(values=colorspace::hex(colorspace::HSV(head(seq(0,360,length.out=ncol(t)+1),-1),.5,1)))+
# ggh4x::force_panelsizes(cols=unit(3,"in"))+ # make bars always 3 inches wide
theme(
  axis.text=element_text(color="black",size=11),
  axis.text.x=element_blank(),
  axis.ticks=element_blank(),
  axis.title=element_blank(),
  legend.position="none",
  panel.border=element_rect(color="gray10",fill=NA,size=.2)
)

ggsave("1.png",width=4.5,height=.25*nrow(t)+.3,limitsize=F)

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 2020-08-24
    • 2014-07-19
    • 1970-01-01
    相关资源
    最近更新 更多