簡體   English   中英

如何強制 ggplot2 連續刻度從 1 開始?

[英]How to force ggplot2 continuous scale to start at 1?

我正在嘗試生成一個 plot ,其中我的連續比例從 1 而不是 0 開始。當我將scale_y_continuous中的限制更改為limits limits=c(1, 7)時,會出現以下消息:

刪除了 7 行包含缺失值 (geom_bar)。

library(ggplot2)
fig4 <- ggplot(AccessToCare, aes(x = reorder(itemShort, mean), y = mean)) 
+ geom_bar(stat = "identity", width = 0.5) 
+ scale_x_discrete(name=" ") 
+ scale_y_continuous(name="Rating", breaks=seq(0,7,1), limits=c(0, 7)) 
+ geom_text(aes(x = itemShort, y = mean + 0.5, label = round(mean, 2)), size = 5) 
+ theme_classic() 
+ theme(text=element_text(size=20)) 
+ coord_flip() 

我確定df中沒有缺失值。

歡迎來到 SO! 該錯誤消息意味着您有一些低於 0 或高於 7 的值,因此在構建ggplot時,它們被 ggplot 過濾掉了。

很難確定這對您的圖表有什么影響,因為您沒有報告我們可以嘗試的任何數據或圖表的圖像。 如果這是一個問題,您可以嘗試在代碼中使用coord_cartesian(ylim = c(0,7))並從scale_y_continuous中刪除limits

但是,要回答您的問題並讓您的比例從 1 而不是 0 開始,您需要通過以下方式更改scale_y_continuous

scale_y_continuous(name="Rating", breaks=1:7, limits=c(0, 7)) 

它回答了你的問題嗎?

如果沒有,請按照本指南提供數據集的可重現示例: 如何制作出色的 R 可重現示例

默認情況下,ggplot2 會刪除超出比例限制的任何值。 尺度中控制越界值發生情況的參數是oob參數。

由於條形圖中的條形通過 xmin/xmax 和 ymin/ymax 在內部參數化為矩形,因此當您將常規比例限制設置為 0 以上時,它會認為 xmin 部分超出范圍。

我在這里回答了一個非常相似的問題,但這里是 tl;dr.

首先我們用一些虛擬數據制作一個 plot

library(ggplot2)

df <- data.frame(x = LETTERS[1:7],
                 y = 1:7)

g <- ggplot(df, aes(x, y)) +
  geom_col() # friendly reminder that this is shorthand for geom_bar(stat = "identity")

這是擠壓越界值的效果,它們被設置為最近的限制。

g + scale_y_continuous(limits = c(1, 7), 
                       oob = scales::squish)

如果您想保持數據不變,您可以使用 function 來返回其輸入不變。 我被允許將其添加到 dev scales庫中。

g + scale_y_continuous(limits = c(1, 7),
                       oob = function(x, ...){x})

您可以使用坐標限制以與上述相同的方式影響限制。

g + coord_cartesian(ylim = c(1, 7))

代表 package (v0.3.0) 於 2020 年 4 月 23 日創建

我相信我不小心找到了一個簡單的解決方案來解決我的查詢並想分享。

我將expand添加到scale_y_continuous

... + scale_y_continuous(name="Rating", breaks=1:7, expand = c(0, -1), limits=c(0,8)) + ...

這導致:

  • y 軸從 1 開始到 7 結束。
  • 從 1 開始到 7 結束的比例標簽。

新圖表

我沒有看到其他地方建議使用負值進行expand ,所以我認為分享它是有價值的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM