gpt4 book ai didi

r - 如何使用 ggplot2 旋转和居中 y 轴标题?

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

我正在尝试旋转 ggplot2 图表的 y 轴标题,并将其置于 y 轴的中心。我已经能够成功旋转标题,但我似乎无法将其置于 y 轴的中心,即使我使用 hjust = 0.5 命令也是如此。有什么想法可以让标题在旋转后在 y 轴上居中吗?

dataset <- data.frame(cultivar = c('var1',
'var1',
'var1',
'var1',
'var3',
'var3',
'var3',
'var3',
'var2',
'var2',
'var2',
'var2',
'var3',
'var3',
'var1',
'var2',
'var2',
'var2',
'var1',
'var2',
'var3',
'var3',
'var1',
'var1',
'var1',
'var3',
'var3',
'var1',
'var2',
'var2',
'var2',
'var2',
'var3',
'var1',
'var3',
'var1'),
rate = c(10,
20,
30,
40,
10,
20,
30,
40,
10,
20,
30,
40,
20,
40,
10,
10,
30,
20,
30,
40,
10,
30,
40,
20,
20,
10,
30,
30,
40,
10,
30,
20,
40,
10,
20,
40),
vi = c(1354,
1307,
1529,
1380,
1416,
1342,
1419,
1363,
1282,
1287,
1202,
1312,
1294,
1248,
1431,
1421,
1287,
1439,
1405,
1406,
1395,
1540,
1222,
1247,
1375,
1235,
1436,
1335,
1478,
1356,
1542,
1219,
1392,
1406,
1524,
1342))

生成图表的代码:

#Aggregate data frame
datasetMean <- aggregate.data.frame(dataset, by=list(dataset$cultivar, dataset$rate), mean)
datasetMean <- select(datasetMean, Group.1, Group.2, vi)
colnames(datasetMean) <- c("cultivar","rate","vi")

#Generate graph
ggplot(datasetMean, aes(x = cultivar, y = vi, fill=factor(rate)))+
geom_bar(stat="identity", width = 0.6, position = "dodge", col = "black")+
scale_fill_discrete(name = "Rate", labels = c("0X","1X","4X","8X"))+
xlab("Cultivar") + ylab("vi")+
ggtitle("VI Scores")+
theme(plot.title = element_text(hjust = 0.5, size = 30),
strip.text.x = element_text(size = 25),
axis.text = element_text(size = 20),
axis.title = element_text(size = 25),
legend.key.size = unit(1.5, "cm"),
legend.text = element_text(size = 15),
legend.title = element_text(size = 20),
axis.title.y = element_text(angle = 0, hjust = 0.5))

最佳答案

如果要垂直移动轴标题,则需要使用 vjust 而不是 hjust,因为它相对于图形面板是垂直的。

axis.title.y = element_text(angle = 0, vjust = 0.5) 添加到您的 theme() 调用应该这样做。

关于r - 如何使用 ggplot2 旋转和居中 y 轴标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58940485/

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