【问题标题】:I need to create a Box plot from this where Area needs to be on X axis, year wise data needs to be in box plot,我需要从中创建一个箱形图,其中区域需要在 X 轴上,年度数据需要在箱形图中,
【发布时间】:2021-11-07 10:54:53
【问题描述】:

这是我的数据框:

df <- structure(list(Area = c("Afghanistan", "Albania", "Algeria", 
"Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", 
"Austria", "Azerbaijan", "Bahamas"), Y1961 = c(9481L, 1706L, 
7488L, 4834L, 92L, 43402L, 0L, 25795L, 22542L, 0L, 138L), Y1962 = c(9414L, 
1749L, 7235L, 4775L, 94L, 40784L, 0L, 27618L, 22627L, 0L, 142L
), Y1963 = c(9194L, 1767L, 6861L, 5240L, 105L, 40219L, 0L, 28902L, 
23637L, 0L, 152L), Y1964 = c(10170L, 1889L, 7255L, 5286L, 95L, 
41638L, 0L, 29107L, 24099L, 0L, 167L), Y1965 = c(10473L, 1884L, 
7509L, 5527L, 84L, 44936L, 0L, 28961L, 22664L, 0L, 173L), Y1966 = c(10169L, 
1995L, 7536L, 5677L, 73L, 46738L, 0L, 30558L, 23785L, 0L, 195L
), Y1967 = c(11289L, 2046L, 7986L, 5833L, 64L, 47437L, 0L, 30443L, 
23949L, 0L, 204L), Y1968 = c(11508L, 2169L, 8839L, 5685L, 59L, 
50357L, 0L, 31344L, 25094L, 0L, 221L)), class = "data.frame", row.names = c(NA, 
-11L))

我想绘制:

Area 需要在 x 轴上,年度数据需要在箱线图中。

我试过了

在 x 轴上使用 Area。但我不确定这里的 Y 轴应该包括什么。

我遗漏了一些我不明白的逻辑。

我正在尝试的代码是

ggplot(country_wise_production1,aes(x=Area, y=))+
geom_boxplot(stat = "identity")+ 
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

但我不确定在 y 轴中包含什么。

【问题讨论】:

  • 图片不是发布数据(或代码)的好方法。请参阅 this Metarelevant xkcd。您可以以dput 格式发布示例数据吗?请使用您尝试过的代码和dput(df) 的输出来编辑问题。或者,如果 dput(head(df, 20)) 的输出太大。 (注意:df 是您的数据集的名称。)
  • 嗨@RuiBarradas。感谢您的回复。我对这种混乱感到抱歉。我是新来的 ggplot(country_wise_production1,aes(x=Area, y=))+geom_boxplot(stat = "identity")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) ) 这是我正在尝试的代码,但我不确定 y 轴要包含什么。 Y 轴需要是这里给定的年份数据。我们不能为 y 轴包含多个列。我们可以吗?

标签: r ggplot2 tidyverse


【解决方案1】:

请在未来考虑 Rui Barradas 的建议。 由于您是初学者,因此您可以这样做:

  1. 使用pivot_longer 将您的数据转换为长格式
  2. 然后使用geom_boxplot:
library(tidyverse)
df %>% 
    pivot_longer(
        cols = -Area, 
        names_to = "years", 
        values_to = "values"
    ) %>% 
    ggplot(aes(x= Area, y=values)) +
    geom_boxplot() +
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 2010-10-31
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    相关资源
    最近更新 更多