我已經使用 ggplot 繪制了一組特定的氣象資料,如下面的 R 代碼中所述。但是,當我使用 scale_fill_brewer 來指定填充顏色時,不會出現圖例。
出現圖例需要哪些更改?
library(tidyverse)
library(lubridate)
library(ggplot2)
library(RColorBrewer)
qurl <- "https://www.geo.fu-berlin.de/met/ag/strat/produkte/qbo/singapore.dat"
sing <- read_table(qurl, skip=4)
# the data file adds a 100mb data row starting in 1997 increasing the number of rows per year from
# 14 to 15. So, one calcuation must be applied to rnum <140 and a different to rnum >140.
sing2 <- sing %>% separate(1,into=c('hpa','JAN'),sep='\\s ') %>% drop_na() %>%
subset(hpa != 'hPa') %>%
mutate(rnum = row_number(),
hpa=as.integer(hpa)) %>%
mutate(year = case_when(rnum <=140 ~ 1987 floor(rnum/14), # the last year with 14 rows of data
rnum >=141 ~ 1987 floor(rnum 10/15))) %>% # the first year with 15 rows of data
relocate(year, .before='hpa') %>% arrange(year,hpa) %>%
pivot_longer(cols=3:14, names_to='month',values_to='qbo') %>%
mutate(date=ymd(paste0(year,'-',month,'-15')),
hpa=as.integer(hpa),
qbo=as.numeric(qbo))
sing2 <- sing %>% separate(1,into=c('hpa','JAN'),sep='\\s ') %>% drop_na() %>%
subset(hpa != 'hPa') %>%
mutate(year=1987 floor(row_number()/15),
hpa=as.integer(hpa)) %>%
relocate(year, .before='hpa') %>% arrange(year,hpa) %>%
pivot_longer(cols=2:13, names_to='month',values_to='qbo') %>%
mutate(date=ymd(paste0(year,'-',month,'-15')),
hpa=as.integer(hpa),
qbo=as.numeric(qbo))
# End Data Massaging. It's ready to be graphed
# A simple call to ggplot with geom_contour_filled generates a legend
sing2 %>%
ggplot(aes(x=date,y=hpa))
geom_contour_filled(aes(z=qbo*0.1))
scale_y_reverse()
# Adding scale_fill_brewer removes the legend.
# Adding show.legend = TRUE to the geom_countour_filled options has no effect.
limits = c(-1,1)*max(abs(sing2$qbo),na.rm=TRUE)
zCuts <- round(seq(limits[1], limits[2], length.out = 11), digits=0)
sing2 %>%
ggplot()
geom_contour_filled(aes(x=date,y=hpa, z = qbo*0.1),breaks=zCuts*0.1)
scale_y_reverse(expand=c(0,0))
scale_x_date(expand=c(0,0), date_breaks = '1 year', date_labels = '%Y')
scale_fill_brewer(palette = 5,type='div',breaks=zCuts)
theme_bw()
theme(legend.position = 'right',
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

uj5u.com熱心網友回復:
OP,鑒于您的示例無法復制(無法訪問您提供的資料),我沒有直接的答案。在地方,我可以給你一些建議的除錯,因為它似乎這個問題是有關breaks=的說法scale_fill_brewer()。正如您所提到的,您在使用時會得到一個圖例geom_contour_filled(),但在添加scale_fill_brewer()部件時不會。
讓我使用
如果你做同樣的事情,但添加一個“無意義的”中斷引數,你會得到相同的情節,但沒有圖例(就像你看到的那樣):
v geom_contour_filled()
scale_fill_brewer(palette = 5, type='div', breaks=1:4)

對我來說,這是很好的證據,表明您的代碼中的問題與breaks=未在預期范圍內的值有關。這只是一個錯字嗎?請注意,breaks=zCuts在 中scale_fill_brewer(),但breaks=zCuts*0.1在geom_contour_filled(). 這將使您的色標的每個值超出輪廓本身的中斷范圍的 10 倍。我愿意打賭,對那條scale_fill_brewer()線的這種改變會奏效:
# earlier plot code
...
scale_fill_brewer(palette = 5,type='div',breaks=zCuts*0.1)
...
# remaining plot code
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315837.html
上一篇:R-ggplot行和列
下一篇:使用gt表繪制每行直方圖-R
