基于ggplot优化图表:设置X轴刻度与绘制涨幅倍数对角线
ggplot散点图:自定义X轴刻度+绘制涨幅倍数对角线
一、自定义X轴刻度
根据你的数据类型(年份或PIBpc数值),用以下两种方式设置:
- 固定间隔刻度:如果X轴是年份(1820-2018),想要每50年显示一个刻度,直接用
scale_x_continuous()指定breaks:
ggplot(your_data, aes(x = year, y = PIBpc)) + # 你已有的散点、标签代码 scale_x_continuous(breaks = seq(1820, 2018, by = 50), # 每50年一个刻度点 labels = seq(1820, 2018, by = 50)) # 刻度显示的文本
要是需要特定年份的刻度,把seq()换成自定义向量就行,比如breaks = c(1820, 1900, 1950, 2000, 2018)。
- 对数刻度(适合数据跨度大的情况):如果PIBpc数值差距极大,用对数轴更清晰,搭配
scale_x_log10():
ggplot(your_data, aes(x = PIBpc, y = ...)) + # 已有代码 scale_x_log10(breaks = c(100, 500, 1000, 5000, 10000), labels = scales::comma) # 用逗号格式化数值,可读性更强
二、绘制涨幅倍数对角线
涨幅倍数线就是y = k*x形式的直线,用geom_abline()直接添加,比如要加2倍、5倍、10倍的虚线:
# 假设你的散点是1820年PIBpc vs 2018年PIBpc ggplot(your_data, aes(x = PIBpc_1820, y = PIBpc_2018)) + # 你已有的散点、标签代码 # 添加倍数虚线 geom_abline(slope = 2, intercept = 0, linetype = "dashed", color = "gray50") + geom_abline(slope = 5, intercept = 0, linetype = "dashed", color = "gray50") + geom_abline(slope = 10, intercept = 0, linetype = "dashed", color = "gray50") + # 给每条线加标签,位置可以自己调整 annotate("text", x = max(your_data$PIBpc_1820)*0.8, y = max(your_data$PIBpc_1820)*0.8*2, label = "2倍", color = "gray50", size = 3) + annotate("text", x = max(your_data$PIBpc_1820)*0.8, y = max(your_data$PIBpc_1820)*0.8*5, label = "5倍", color = "gray50", size = 3)
如果是时间序列散点(X是年份,Y是PIBpc),要标记某段时间的涨幅倍数,先算出基准年份的PIBpc值,再对应画直线就行,比如1820年到2018年的10倍线,用geom_segment()实现:
ggplot(your_data, aes(x = year, y = PIBpc)) + # 已有代码 geom_segment(aes(x = 1820, xend = 2018, y = your_data$PIBpc[your_data$year == 1820], yend = 10*your_data$PIBpc[your_data$year == 1820]), linetype = "dashed", color = "gray50")
内容的提问来源于stack exchange,提问作者alejandro101
相关产品推荐
相关产品推荐

