gpt4 book ai didi

R:如何更改facet_grid中每行的列数

转载 作者:行者123 更新时间:2023-12-04 11:16:42 24 4
gpt4 key购买 nike

通过ggplot,我使用下面的代码绘制了如下图。但是如果我这样绘制,我根本看不到 x 轴。我想知道是否有任何方法可以解决这个问题,例如更改每行中的列数。我试过ncol facet_grid 中的命令但它不允许我这样做。

ggplot(derivative, aes(x = factor(move), fill = factor(move)), colour = black)+ 
geom_bar()+
facet_grid(Market~Season)+
scale_fill_discrete(name="Relative Market Move",
breaks=c("neg.big", "neg.small", "pos.big", "pos.small"),
labels=c("Big Negative", "Small Negative", "Big Positive", "Small Positive"))+
scale_x_discrete(labels=c("Large Negative", "Small Negative", "large Positive", "Small Positive"))+
labs( x = "") +ylab("Count")

cramped faceted plot

最佳答案

使用堆叠条形图和“负数”的条形向下可能会更好。这将更有效地使用水平空间并更容易查看时间趋势。例如:

library(reshape2)

首先创建一些假数据:
set.seed(199)
dat = data.frame(index=rep(c("S&P 500","Shanghai","Hang Seng"), each=7),
year=rep(paste0(rep(2009:2015,each=2),rep(c("Sp","Au"),7)), 3),
replicate(3, sample(50:100,14*3)))
dat$big.neg = 300 - rowSums(dat[,3:5])
names(dat)[3:5] = c("big.pos","small.pos","small.neg")

# Set year order
dat$year = factor(dat$year, levels=dat$year[1:14])

# Melt to long format
dat = melt(dat, id.var=c("year","index"))

现在的情节:
ggplot() +
geom_bar(data=dat[dat$variable %in% c("big.pos","small.pos"),],
aes(x=year, y=value, fill=rev(variable)), stat="identity") +
geom_bar(data=dat[dat$variable %in% c("big.neg","small.neg"),],
aes(x=year, y=-value, fill=variable), stat="identity") +
geom_hline(yintercept=0, colour="grey40") +
facet_grid(index ~ .) +
scale_fill_manual(breaks=c("big.neg","small.neg","small.pos","big.pos"),
values=c("red","blue","orange","green")) +
scale_y_continuous(limits=c(-200,200), breaks=seq(-200,200,100),
labels=c(200,100,0,100,200)) +
guides(fill=guide_legend(reverse=TRUE)) +
labs(fill="") + theme_bw() +
theme(axis.text.x=element_text(angle=-90, vjust=0.5))

enter image description here

关于R:如何更改facet_grid中每行的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39060309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com