我正在尝试为不同的数据子集生成一个y轴直方图。
我一直遵循这里的指示:How to automatically adjust the width of each facet for facet_wrap?
但我似乎不能让轴上的刻痕起作用。
score <- rep(c(0,1,2,3,4,5,6,7,8), c(20424, 1636, 1864, 989, 397, 174, 69, 18, 4))
damage <- rep(c("No damage", "damage"), c(20424, 5151))
damage <- ordered(damage, c("No damage", "damage"))
df <- data.frame(score, damage)
library(ggplot2)
library(ggforce)
#The following produces the graph as I would like it but there are no ticks or tick labels
#on the x-axis
df %>%
ggplot(aes(x = score)) +
geom_histogram(binwidth = 1) +
scale_x_discrete(name = "Score") +
scale_y_continuous(name = "") +
ggforce::facet_row(vars(damage), scales = 'free', space = 'free')

##Whereas this gives me the tick marks and labels but messes up my graph
df %>%
ggplot(aes(x = score)) +
geom_histogram(binwidth = 1) +
scale_x_discrete(name = "Score",
limits = c(0,1,2,3,4,5,6,7,8)) +
scale_y_continuous(name = "") +
ggforce::facet_row(vars(damage), scales = 'free', space = 'free')

我尝试过许多排列,使用和不使用ggforce::facet_row选项,但我似乎无法使它工作。
如有任何建议,将不胜感激。
发布于 2022-04-19 16:30:34
首先,您的x轴是continuous,@Axeman已经在注释中提到了。我建议使用facet_row of ggforce,因为这也将显示第二个图的y轴,如下所示:
library(ggplot2)
library(ggforce)
df %>%
ggplot(aes(x = score)) +
geom_histogram(binwidth = 1) +
scale_x_continuous(name = "Score", breaks = 0:8) +
ggforce::facet_row(vars(damage), scales = 'free', space = 'free')输出:

如果使用facet_grid,它不会显示像她这样的第二个直方图的标签:
library(ggplot2)
library(ggforce)
df %>%
ggplot(aes(x = score)) +
geom_histogram(binwidth = 1) +
scale_x_continuous(name = "Score", breaks = 0:8) +
facet_grid(cols = vars(damage), scales = 'free', space = 'free')输出:

https://stackoverflow.com/questions/71927236
复制相似问题