问题描述
首先我在 sjplot 中使用 set.theme() 为我的 ggplots 设置主题:
# library(ggplot2)
# library(RColorBrewer)
# library(sjplot)
# library(tidyr)
set_theme(
geom.outline.color = "antiquewhite4",geom.outline.size = .5,geom.label.size = 1.5,geom.label.color = "blue50",title.color = "blue",title.size = 1.5,title.align = 'center',# axis.angle.x = 90,axis.textcolor = "blue",axis.textsize = 1.15,base = theme_bw(),)
从这段代码中我不清楚是否应该绘制其他每个 x 轴标签。当列类为整数时,这是result,每隔一年标记一次。解决方法是将类更改为字符,将其绘制为 correctly。这是数据框:
df<-structure(list(Year = c(2012L,2012L,2013L,2014L,2015L,2016L,2017L,2018L,2019L,2020L,2020L),Type = c("Cool,Cold Below\nnormal Temperatures","Insects","Tornadoes","Lightning","Frost,Freezing","Heat,Excessive Heat,\nHigh Temp,Low Humidty","Fire,Wildfire","Wind,High Winds","Hail","Excessive Rain,\nMoisture,Humidty","Flood,\nFlash Flooding","Drought","Cool,"Drought"),`Number of Counties` = c(0L,0L,3L,1L,5L,19L,8L,10L,9L,4L,24L)),row.names = c(NA,-108L),class = c("tbl_df","tbl","data.frame"))
还有我的代码
# check class
class(df$Year) # [1] "integer"
## ggplot
# interpolate a color palette
colourCount = length(unique(df$Type))
getPalette = colorRampPalette(brewer.pal(10,"RdBu"))
# make plot
ggplot(df)+
geom_bar(aes(x=Year,y=`Number of Counties`,fill=Type),stat="identity") +
scale_fill_manual(values = getPalette(colourCount)) +
theme(axis.text.x = element_text(angle = 45,vjust = 1,hjust=1),legend.key.height=unit(.75,"cm"))+
ggtitle('VT disaster Designations: 2012-2020\nNote some counties have more than one\ndisaster type per year')
#change year class to character
df$Year<-as.character(df$Year)
ggplot(df)+
geom_bar(aes(x=Year,"cm"))+
ggtitle('VT disaster Designations: 2012-2020\nNote some counties have more than one\ndisaster type per year')
对于 sjplot 和/或 ggplot 正在发生的事情的任何帮助表示赞赏。
解决方法
我不知道为什么该类让您的绘图跳过所有其他 x 轴刻度/标签,但您可以通过使用 scale_x_continuous(breaks = ...)
指定 x 轴中断来解决它。
# your current code with df$Year as integer
p <- ggplot(df)+
geom_bar(aes(x=Year,y=`Number of Counties`,fill=Type),stat="identity") +
scale_fill_manual(values = getPalette(colourCount)) +
theme(axis.text.x = element_text(angle = 45,vjust = 1,hjust=1),legend.key.height=unit(.75,"cm"))+
ggtitle('VT Disaster Designations: 2012-2020\nNote some counties have more than one\ndisaster type per year')
# specify the x-axis breaks
p + scale_x_continuous(breaks = 2012:2020)
p + scale_x_continuous(breaks = df$Year) # alternative