# library
library(ggplot2)
library(dplyr)
# Start with the diamonds dataset, natively available in R:
p <- diamonds %>%
# Add a new column called 'bin': cut the initial 'carat' in bins
mutate(bin=cut_width(carat, width = 0.5, boundary=0) ) %>%
# plot
ggplot(aes(x=bin, y= x) )
geom_boxplot()
xlab("Carat") geom_abline(slope = 1, intercept = 0)
p
我嘗試使用geom_abline
添加 45 度對角線。這會產生一條黑線。bin
但是,這與x 軸上的不完全匹配。例如,當 時bin = (2.5,3]
,黑線的 y 坐標為 6。
我粗略地畫了(藍色)我認為應該是 45 度對角線的位置。例如,對于bin = (2.5, 3]
,y 坐標應為 2.75(bin 的中點)。對于bin = (3, 3.5]
,y 坐標應為 3.25(bin 的中點)。有沒有辦法在ggplot中產生這條線?
uj5u.com熱心網友回復:
對于ggplot
,軸上的任何類別的距離都是 1。因此geom_abline
,斜率為 1 時,y 軸會增加每個類別的 1。由于您的垃圾箱大小為 1/2,因此使用斜率0.5
將正確繪制斜率。
我們還需要將截距調整為-0.25
。這是因為第一個 bin 位于 x 坐標 1,而不是 0.25。
p <- diamonds %>%
# Add a new column called 'bin': cut the initial 'carat' in bins
mutate(bin=cut_width(carat, width = 0.5, boundary=0) ) %>%
# plot
ggplot(aes(x = bin, y = x))
geom_boxplot()
xlab("Carat")
geom_abline(slope = 0.5, intercept = -0.25)
geom_hline(yintercept = c(2.75, 3.25))
請注意,我還繪制了 2 條水平線以確認這符合您手動計算的示例值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468215.html
上一篇:使用ggplot2和geom_bar根據1個因子變數和基于另一個因子變數的條形圖案更改條形顏色
下一篇:如何讓x軸顯示資料集中的所有月份