Dat*_*aTx 1 r histogram ggplot2
有几个问题询问如何更改 ggplot x 轴刻度,但我遇到了麻烦,可能是因为我用来绘图的其他美学。我想将 x 轴刻度从 7 扩展到 25。
我正在使用以下向量:
var <- c(2,2,1,0,1,1,1,1,1,3,2,3,3,5,1,4,4,0,3,4,1,0,3,3,0,0,
1,3,2,6,2,2,2,1,0,2,3,2,0,0,0,0,3,2,2,4,3,2,2,0,4,1,0,1,3,1,4,3,1,2,
6,7,6,1,2,2,4,5,3,0,6,5,2,0,7,1,7,3,1,4,1,1,2,1,1,2,1,1,4,2,0,3,3,2,2,2,5,3,2,5,2,5)
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码制作一个直方图,其中 x 轴刻度位于条形下方
df <- data.table(x = var)
df <- df[, .N, by=x]
p <- ggplot(df, aes(x=factor(x), y=N)) +
geom_bar(stat="identity", width=1.0,
colour = "darkgreen",
fill = 'lightslateblue')
p <- p + labs(title = "hello world", x = "x tick", y = "ytick")
print(p)
Run Code Online (Sandbox Code Playgroud)
当我打印直方图时,我希望 x 轴刻度达到 25

我尝试使用coord_cartesian(xlim = c(-0, 25))但它没有正确绘制,因为我希望沿着 x 轴标记刻度。

问题是您正在转换x为美学调用中的一个因素。您可以通过事先指定您想要的“级别”并确保它们不会被删除(来自这个问题)来解决这个问题:
df$x <- factor(df$x, levels=c(0:25))
p <- ggplot(df, aes(x=x, y=N)) +
geom_bar(stat="identity", width=1.0,
colour = "darkgreen",
fill = 'lightslateblue')
p <- p + labs(title = "hello world", x = "x tick", y = "ytick") +
scale_x_discrete(drop=FALSE) + ylim(c(0, 50))
print(p)
Run Code Online (Sandbox Code Playgroud)
这将为您提供扩展的直方图。

我不确定你为什么要以这种迂回的方式生成直方图:
p <- qplot(var, geom="histogram") + xlim(c(0, 25)) + ylim(c(0, 50))
Run Code Online (Sandbox Code Playgroud)

编辑:将 ylim 更改为 0-50。