gpt4 book ai didi

r - 如何在没有手动限制的情况下在一侧而不是另一侧扩展 ggplot 条形刻度

转载 作者:行者123 更新时间:2023-12-04 10:48:17 26 4
gpt4 key购买 nike

目标是消除刻度线和条形底部之间的空间,而不切断条形另一端之外的任何百分比标签。

我正在使用 R 的 ggplot2 运行数十个条形图,并尝试遵循我们的组织风格指南,该指南是使用 Excel 为每个图表手动开发的。最大长度条在不同图表中的长度不同,并且可能随着源数据的变化而变化,所以我不想手动设置限制。 [也许这里有一个解决方法:有没有办法根据输入自动调整限制?]

我已经咨询过:

Removing negative plot area in ggplot2

How to remove space between axis & area-plot in ggplot2?

Force the origin to start at 0 in ggplot2 (R)

http://docs.ggplot2.org/dev/vignettes/themes.html

从以下代码生成几乎可以工作的图表。出于公共(public)目的,我使用 MASS 包中的“quine”数据集。首先,我按年龄分组找到女性的百分比。然后我按女性百分比对年龄组进行排序。

require(MASS)
attach(quine)
p.SexAge <- prop.table(table(Sex, Age), 2)
perc.SexAge <- round(p.SexAge * 100)

perc.SexAge.flattened <- as.data.frame(perc.SexAge)
perc.SexAge.flattened.F <- subset(perc.SexAge.flattened, Sex == "F")
require(ggplot2)

ggplot(data=perc.SexAge.flattened.F, aes(x=reorder(Age, -Freq), y=Freq)) +
geom_bar(stat="identity", fill = "#00ABE1") +
scale_x_discrete(expand = c(0, 0)) +
scale_y_continuous(expand = c(0,6)) +
ggtitle("Percent Female By Age") +
ylab("Percent Female") +
xlab("Age Group\n") +
#theme_classic() +
theme(plot.margin = unit(c(0,0,0,0), "in")) +
coord_flip() +
geom_text(aes(label = Freq), vjust = 0.4, hjust = - 0.4, size = 3.5)

default theme

当取消注释 theme_classic() 以创建空白区域以满足我们的样式指南时,很明显在垂直轴刻度线和条形底部之间存在过多的空间。如果有更多的条(未显示),这个问题会变得更糟。

class theme

如果我将 scale_y_continuous(expand = c(0,6)) 更改为
scale_y_continuous(expand = c(0,0)) ,
标签在最长的条上被切掉,
违反组织风格指南。

chopped off label

最佳答案

注意:expand 的实现将随着即将发布的 ggplot2 的发布而改变2.3.0 版本,两端都将具有灵 active 。以下答案将继续有效,但不再需要。见 ?expand_scale .
expand不会成为你的 friend ,因为这两个参数是双方的乘法和加法扩展常数。所以c(0, 6)将始终在每侧添加 6 个单位。连续数据的默认值为 c(0.05, 0)两端的范围增加 5%。

我们可以预先计算所需的范围。左边界应始终设置为 0,我们将右边界设置为 max + 6。(如果图之间的范围变化很​​大,您也可以使用乘法因子。)

lim <- c(0, max(perc.SexAge.flattened.F$Freq) + 6)
#lim <- c(0, max(perc.SexAge.flattened.F$Freq) * 1.1) # 10% increase

ggplot(data=perc.SexAge.flattened.F, aes(x=reorder(Age, -Freq), y=Freq)) +
geom_bar(stat="identity", fill = "#00ABE1") +
scale_x_discrete(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0), limits = lim) + #This changed!
ggtitle("Percent Female By Age") +
ylab("Percent Female") +
xlab("Age Group\n") +
theme_classic() +
theme(plot.margin = unit(c(0,0,0,0), "in")) +
coord_flip() +
geom_text(aes(label = Freq), vjust = 0.4, hjust = - 0.4, size = 3.5)

enter image description here

p.s.请不要使用 attach ,尤其是在其他人加载到他们的环境中的代码上。

关于r - 如何在没有手动限制的情况下在一侧而不是另一侧扩展 ggplot 条形刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561030/

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