如何在ggplot中添加颜色并更改刻度之间的空间?

时间:2021-06-02 00:36:50

标签: r ggplot2 plot

我目前正在学习 r,我尝试用 ggplot() 生成时间序列图,这是我当前的代码:

library(readxl)
library(ggplot2)

AUS_GDP <- c(826, 834, 858, 886, 936, 982, 999, 1030, 1057, 1114, 1352, 
1398, 1428, 1435, 1508, 1825, 1793, 1881, 1857, 1733, 2190, 1868, 
1704, 1975, 2246, 2310, 2554, 2954, 3381, 3339, 3148, 3736, 4382, 
4798, 4202, 3988, 4866, 4294, 3661, 4728, 4613, 4544, 4368, 4352, 
4616, 4403, 4532, 4956, 5031, 4932, 5217, 5259, 5663, 6095, 6113, 
6596, 6387, 6433, 6817, 6703, 6830, 7101, 6476, 7133, 6861, 7049, 
6900, 7383, 7179, 7567, 7106, 7438, 6368, 5910, 6003, 5558, 5874, 
5451, 6202, 6121, 6397, 6119, 6094, 6497, 6846, 6825, 7184, 7358, 
7481, 7940, 8305, 8136, 8126, 8220, 8013, 7806, 7775, 7637, 7336, 
7517, 7597, 7828, 8072, 8276, 8635, 8851, 8883, 8837, 8690, 8389, 
7504, 6940, 7275, 7718, 8066, 8477, 8792, 9159, 9382, 9318, 9828, 
10820, 11963, 12278, 11735, 11026, 10512, 10622, 11105, 11536, 
11815, 11966, 11824, 11963, 12419, 12795, 12924, 12895, 13238, 
13753, 14013, 13793, 14389, 14983, 15699, 16182, 16324, 17108, 
17770, 18428, 19166, 19590, 19772, 20527, 20698, 20993, 21613, 
21592, 21948, 22826, 22972, 23368, 22972, 22697, 24009, 24927, 
25116, 25971, 26702, 27407, 27373, 26861.2749592856, 27560.1782773384, 
28622.4757584582, 29844.1713244349, 30690.0624398521, 31740.4697474047, 
32857.9937806025, 34337.139432097, 35551.0195059737, 36603.0449959447, 
37275.9912489095, 38567.0654883377, 39523.6551974459, 40887.725336397, 
41904.4458707113, 42650.9859308496, 44033.5837617713, 44421.6404707281, 
44686.541383463, 45400.2233987967, 46132, 46999, 47250, 47867, 
48357, 48845, 49265.6135020065, 49830.7993065638)
log_AUS_GDP <- log(AUS_GDP)
year <- 1820:2018
AUS <- data.frame(year = year, 
                  gdp = AUS_GDP,
                  log_gdp = log_AUS_GDP)


ggplot(AUS, aes(x = year, y = gdp)) +
  geom_line() + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.1, size = 10)) +
  scale_x_continuous("year", labels = as.character(year), breaks = year)

这是我现在所拥有的: enter image description here

我希望实现这样的目标; enter image description here

但我不知道该怎么做,有人可以给我指路吗?非常感谢!

2 个答案:

答案 0 :(得分:0)

我认为每个国家/地区都有不同的数据框。您可以将它们与一个 country 列组合在一个数据框中,该列标识每个数据集并使用 ggplot 绘制它们。

library(dplyr)
library(ggplot2)

bind_rows(lst(AUS, US, FRANCE), .id = 'country') %>%
  ggplot(aes(year, gdp, color = country)) + 
  geom_line() + 
  labs(x = 'YEAR', 
       y = 'GDP', 
       title = 'GDP per Capita in France, UK and the US')

答案 1 :(得分:0)

保持简单:如下所示: 我添加了一个带有 Country Aus

的列
ggplot(AUS, aes(x = year, y = gdp, color=Country)) +
  geom_line() +
  theme_minimal() +
  theme(legend.position="bottom")

enter image description here

相关问题