使用条形图绘制时间序列值

时间:2016-01-28 17:05:36

标签: r ggplot2

我想使用条形图绘制一些时间序列数据来显示随时间的变化,但我在使用ggplot2时遇到了麻烦。

示例数据:

df <- structure(list(year = c(1910, 1911, 1912, 1913, 1914, 1915, 1916, 
1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 
1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 
1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 
1950, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918), 
    dday_30 = c(48.3156566976744, 28.4325095348837, 10.9345420465116, 
    30.3018175813953, 22.3314346511628, 6.33566069767442, 27.4823442325581, 
    23.7263461860465, 20.3016930232558, 38.8897564651163, 6.69049065116279, 
    18.4395965581395, 25.8079846046512, 3.57936218604651, 16.6990909767442, 
    21.2175313023256, 15.2260691627907, 9.26520976744186, 9.79716334883721, 
    18.9872194883721, 22.5747300465116, 47.8516541860465, 30.8272055348837, 
    28.0607320930233, 50.1987654883721, 29.4361414418605, 58.4356670232558, 
    45.2513310697674, 29.4801361860465, 44.2652285116279, 38.7353984186047, 
    17.164524372093, 18.8734693488372, 38.7099044186047, 26.9970333953488, 
    13.3448749767442, 31.4876399534884, 29.700936, 26.0668504651163, 
    24.7630490232558, 15.4445029767442, 37.5025793548387, 22.0377372580645, 
    8.63075717741935, 24.8010268548387, 15.4514439516129, 5.60195516129032, 
    21.3893638709677, 18.4909673387097, 19.3719947580645)), .Names = c("year", 
"dday_30"), row.names = c(NA, 50L), class = "data.frame")

以下是我尝试的内容:

ggplot(stack, aes(x = year, y = dday_30)) + geom_bar()

但是告诉我不能有y aesthetic

  

错误:stat_count()不得与y美学一起使用。

有没有办法用时间序列数据做到这一点?

1 个答案:

答案 0 :(得分:2)

首先,您需要使用aggregatedday_30平均year列:

library(ggplot2)

df_melted <- aggregate(data = df, dday_30 ~ year, mean)
names(df_melted) <- c("year", "mean_dday_30")

然后,正如@Henrik在评论中指出的那样,您可以使用stat = "identity"制作条形图:

ggplot(df_melted, aes(x = year, y = mean_dday_30)) +
  geom_bar(stat = "identity")

Plot1

但是,对于这种类型的数据,折线图可能是更好的选择:

ggplot(df_melted, aes(x = year, y = mean_dday_30)) +
  geom_line() +
  geom_point()

Plot2