x轴标签从r中的ggplot2条形图移开
x-axis labels shifted off ggplot2 bar chart in r
我正在使用 geom_bar 来绘制对关于引入非本地物种作为害虫控制的调查的响应频率。我正在研究对这个问题的回答如何因人们居住的地方而异。示例数据 here.
我想自定义条形图上的 x 轴标签。但是,在尝试指定新值时,它们要么消失,要么完全向右移动。如果我按原样 运行 代码,在下面,x 轴会自动填充 pest.intro.nonnat 值(-2、-1、0、1、2),如图 1 所示。
但是,如果我激活 scale_x_discrete()
,那么我将丢失任何 x 轴标签(图 2)。如果我激活 xlim()
,那么我会得到我想要的标签,但它们会向右偏移 4 个空格(图 3)。
谁能帮我把我想要的标签放在合适的地方?谢谢!
p + geom_bar(aes(fill = desc.p18), stat = "count",
position = "stack", col = "black") +
scale_fill_brewer(palette = "Dark2",
labels = legend,) +
# scale_x_discrete(labels = c("a", "b", "c", "d", "e")) +
# xlim("a", "b", "c", "d", "e") +
labs(title = "pest.intro.nonnat",
y = "Number of responses") +
theme(legend.title = element_blank(),
legend.text = element_text(size = 10),
axis.title.x = element_blank(),
axis.text.x = element_text(size=10, angle=45))
如果您想使用 scale_x_discrete
,请确保您的 x 值在因子中。
ggplot(dat, aes(x=as.factor(pest.intro.nonnat))) +
geom_bar(aes(fill = desc.p18), stat = "count", position = "stack", col = "black") +
scale_x_discrete(labels = c("a", "b", "c", "d", "e"))
我正在使用 geom_bar 来绘制对关于引入非本地物种作为害虫控制的调查的响应频率。我正在研究对这个问题的回答如何因人们居住的地方而异。示例数据 here.
我想自定义条形图上的 x 轴标签。但是,在尝试指定新值时,它们要么消失,要么完全向右移动。如果我按原样 运行 代码,在下面,x 轴会自动填充 pest.intro.nonnat 值(-2、-1、0、1、2),如图 1 所示。
但是,如果我激活 scale_x_discrete()
,那么我将丢失任何 x 轴标签(图 2)。如果我激活 xlim()
,那么我会得到我想要的标签,但它们会向右偏移 4 个空格(图 3)。
谁能帮我把我想要的标签放在合适的地方?谢谢!
p + geom_bar(aes(fill = desc.p18), stat = "count",
position = "stack", col = "black") +
scale_fill_brewer(palette = "Dark2",
labels = legend,) +
# scale_x_discrete(labels = c("a", "b", "c", "d", "e")) +
# xlim("a", "b", "c", "d", "e") +
labs(title = "pest.intro.nonnat",
y = "Number of responses") +
theme(legend.title = element_blank(),
legend.text = element_text(size = 10),
axis.title.x = element_blank(),
axis.text.x = element_text(size=10, angle=45))
如果您想使用 scale_x_discrete
,请确保您的 x 值在因子中。
ggplot(dat, aes(x=as.factor(pest.intro.nonnat))) +
geom_bar(aes(fill = desc.p18), stat = "count", position = "stack", col = "black") +
scale_x_discrete(labels = c("a", "b", "c", "d", "e"))