因此,我正在尝试制作一个分组条形图,x轴上为Year,y轴上为Number,按Nationality分组,并按Municipality分面。下面是数据(2017年在中间,所以没有显示)。
> head(pres_munic)
Year Municipality Nationality Number
1 2016 Tapachula, Chiapas Salvadoran 2141
2 2016 Acayucán, Veracruz Salvadoran 4697
3 2016 Tuxtla Gutiérrez, Chiapas Salvadoran 2327
4 2016 Centro, Tabasco Salvadoran 1811
> tail(pres_munic)
Year Municipality Nationality Number
1328 2018 San Pedro Tapanatepec, Oaxaca Honduran 365
1329 2018 Huehuetán, Chiapas Honduran 417
1331 2018 Iztapalapa, CDMX Honduran 247
1332 2018 Saltillo, Coahulia Honduran 352由于某些原因,ggplot2在一个刻度上将x轴设置为"2016“,然后在下一个刻度上设置为"2016.5”,依此类推,直到2018.5。我不知道它为什么这样做,因为在我的年份变量中,我在任何年份之后都没有.5。Here是我的粗略图的样子,它在底部显示了奇怪的轴。
我的代码如下,如果乱七八糟的话很抱歉。
ggplot(pres_munic, aes(Year, Number)) + facet_wrap(~ Municipality) + geom_bar(aes(fill = Nationality),
width = 0.4, position = position_dodge(width=0.5), stat="identity") +
theme(legend.position="top", legend.title =
element_blank(),axis.title.x=element_blank(),
axis.title.y=element_blank())有谁知道我该怎么改变这一点?或者至少让轴只显示2016,2017,2018?提前感谢!
发布于 2018-06-20 03:52:12
因为Year是数值型的,所以ggplot会将其解释为可以用小数点拆分的连续数据。为了防止这种情况,我们可以使用scale_x_continuous指定刻度线的位置
ggplot(pres_munic, aes(Year, Number)) +
facet_wrap(~ Municipality) +
geom_bar(aes(fill = Nationality), width = 0.4, position = position_dodge(width=0.5), stat="identity") +
scale_x_continuous(breaks = 0:2100) +
theme(legend.position="top", legend.title =
element_blank(),axis.title.x=element_blank(),
axis.title.y=element_blank())发布于 2020-05-14 08:03:37
如果有很多年,这个解决方案看起来会很糟糕。您可能希望使用ggplot的自动日期缩放功能。
pres_munic$Date <- as.Date(paste(pres_munic$Year, 1, 1, sep="-"))
ggplot(pres_munic, aes(Date, Number)) +
facet_wrap(~ Municipality) +
geom_bar(aes(fill = Nationality), width = 0.4, position = position_dodge(width=0.5), stat="identity") +
scale_x_date(date_labels = "%Y") +
theme(legend.position="top", legend.title =
element_blank(),axis.title.x=element_blank(),
axis.title.y=element_blank())https://stackoverflow.com/questions/50935857
复制相似问题