我正在努力研究如何在geom_histogram. 我想旋轉標簽,它應該在每個欄的頂部。我正在使用以下代碼:
玩具示例:
ex_tfdp = data.frame(x=rnorm(1000,10,10))
ggplot(ex_tfdp)
geom_histogram(aes(x = x), boundary = 0,binwidth = 5, color="black", fill="#FFC857")
stat_bin( geom="text", colour="black", size=3.5,
aes(x = x,label=..count..), angle = 90, vjust = -1.5)
theme(axis.text.x = element_text(angle = 90, hjust = .5),
panel.background = element_blank(),
legend.position="bottom",
legend.title=element_blank(),
axis.ticks.y=element_blank())

關于如何更改這些值的角度并將它們放在每個條形頂部的任何提示?
uj5u.com熱心網友回復:
我們沒有您的資料,但假設它類似于以下內容:
set.seed(2)
my_data <- data.frame(measure = rexp(20000)^1.2 * 150)
然后,您可以通過切換到geom_text并使用stat = "bin". 然后你仍然可以breaks作為引數傳遞給 stat。這允許您使用geom_text引數angle旋轉 90 度。阿位hjust和vjust扭捏然后得到您的標簽正確的:
ggplot(my_data)
geom_histogram(aes(x = measure), boundary = 0,
binwidth = 100, color="black", fill="#FFC857")
geom_text(stat = "bin", colour = "black", size = 3.5,
breaks = seq(0,2100,100), hjust = -0.5,
aes(x = measure, label=..count..), vjust = 0.5, angle = 90)
scale_x_continuous(breaks = seq(0,2100,100),
labels = seq(0,2100,100),
expand = expansion(add = c(0, 0)))
scale_y_continuous(limits = c(0, 15000))
theme(axis.text.x = element_text(angle = 90, hjust = .5),
panel.background = element_blank(),
legend.position="bottom",
legend.title=element_blank(),
axis.ticks.y=element_blank())

uj5u.com熱心網友回復:
我簡化了你的例子:
require(ggplot2)
require(gridExtra)
set.seed(15)
ex_tfdp = data.frame(x=rnorm(1000,10,10))
original.plot = ggplot(ex_tfdp)
geom_histogram(aes(x = x), boundary = 0,binwidth = 5, color="black", fill="#FFC857")
stat_bin( geom="text", colour="black", size=3.5,
aes(x = x,label=..count..), angle = 90, vjust = -1.5)
new.plot = ggplot(ex_tfdp)
geom_histogram(aes(x = x), boundary = 0, binwidth = 5) ylim(c(0, 220))
stat_bin( geom="text", colour="black", size=3.5,
aes(x = x,label=..count..), angle = 90, boundary = 0, binwidth = 5, hjust = -.5)
grid.arrange(original.plot, new.plot, ncol=2)

這里的關鍵是在添加圖層時保留boundary = 0和。binwidth = 5stat_bin
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368359.html
