我有這個資料:
structure(list(date = structure(c(18474, 18832, 18861, 18666,
18597, 18517, 18938, 18611, 18384, 18768, 18633, 18545, 18550,
18577, 18354, 18584, 18821, 18338, 18815, 18591, 18799, 18721,
18945, 18448, 18445, 18765, 18784, 18683, 19012, 18505, 18991,
18346, 18899, 18470, 18514, 18774, 18943, 18834, 18424, 18506,
18844, 18988, 18418, 18951, 18678, 18454, 18552, 19021, 18414,
18958), class = "Date"), value = c(10, 28, 87, 105, 345, 40,
592, 220, 5, 51, 160, 78, 91, 529, 51, 552, 13, 13, 7, 435, 11,
250, 848, 7, 5, 60, 25, 145, 1493, 22, 186, 44, 138, 9, 29, 40,
779, 29, 2, 22, 38, 164, 2, 1058, 126, 7, 98, 2502, 2, 1010)), row.names = c(NA,
-50L), class = c("tbl_df", "tbl", "data.frame"))
一個簡單的
ggplot(df, aes(date, value)) geom_col()
給出了這個:

但是,我希望每 1000 間隔從 -2000 到 2000。對于負值,我想繪制水平網格線,但是我不想在 y 軸上標記這些間隔。所以我做了以下事情:
ggplot(df, aes(date, value))
geom_col()
scale_y_continuous(
limits = c(-3000,3000),
breaks = c(-2000, -1000, 0,1000,2000),
labels = function(x){
if(x < 0){
return("")
}else{
return(x)
}
}
)
但這不起作用說:Error: Breaks and labels are different lengths Run rlang::last_error() to see where the error occurred. In addition: Warning message: In if (x < 0) { : the condition has length > 1 and only the first element will be used
我認為它會以某種方式檢查每個中斷,我可以從這個函式回傳標簽。
我可以做這個:
ggplot(df, aes(date, value))
geom_col()
scale_y_continuous(
limits = c(-3000,3000),
breaks = c(-2000, -1000, 0,1000,2000),
labels = c("", "", 0, 1000, 2000)
)
這給出了所需的輸出:

但我不認為這是最好的選擇。
uj5u.com熱心網友回復:
這是因為if沒有矢量化,請在運行上面的破壞代碼時查看警告訊息:
警告訊息:在
if (x < 0){ :條件有length > 1并且只使用第一個元素
您應該使用ifelse回傳一個大小為x.
ggplot(df, aes(date, value))
geom_col()
scale_y_continuous(
limits = c(-3000,3000),
breaks = c(-2000, -1000, 0,1000,2000),
labels = function(x) ifelse(x < 0, "", x)
)

uj5u.com熱心網友回復:
您可以使用replace:
ggplot(df, aes(date, value))
geom_col()
scale_y_continuous(
limits = c(-3000,3000),
breaks = seq(-2000, 2000, 1000),
labels = function(x) replace(x, which(x < 0), "")
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427630.html
