【问题标题】:Barplot form data in a dataframe数据框中的条形图表单数据
【发布时间】:2021-02-24 13:58:09
【问题描述】:

我在一个数据框中有以下数据;

TYPE_OF_COMPANY    COUNT_OF_COMPANIES
    
AIM-Listed                  876
Charitable-organisation          82
Industrial-Provident             50
Limited-Partnership               2
Limited by Guarantee            277
Limited Liability Partnership   167
Listed-LSE                     1131
Not-Companies-Act                75
Private Limited Company        1163
Public-Unlisted                 418
Royal-Charter                     5
Unlimited                       111

我想将此数据表示为条形图。当此数据在表中时,我的代码成功,但我在排序数据时遇到问题,但我对使用以下代码的输出感到满意:

barplot(counts,  
        Xlab='TYPES_OF_COMPANIES', ylab='TYPE_OF_COMPANY', ylim=c(0,1200),
        names.arg = c("LP", "RC", "IP", 
          "N-C-A", "C-O", "Guarantee", 
              "U-L", "C-O",
              "LLP","L-G","P-U",
               "A-L", "LSE", "PL"),
        main='Number of Different Types of Companies in the database')

当我尝试修改代码以使用数据框时,它给了我一个错误。我知道我可以使用 ggplot2 包来做到这一点,但这是为了说明,我想在基础 R 中做到这一点。

您可以告诉我如何对表格进行排序或如何使条形图与数据框一起使用。

非常感谢任何帮助。

【问题讨论】:

  • barplot(height = your_data$COUNT_OFCOMPANIES, names.arg = your_data$TYPE_OF_COMPANY)。或者,您可以使用 sort() 函数对表进行排序。

标签: r bar-chart


【解决方案1】:

您可以这样做,而不是编写 names.arg:

labs <- c("AIM", "Charity", "I-P", "L-P", "L-G", "LLP",  
            "L-LSE", "NCA", "PLC", "P-UL", "RC", "UL")

new_df <- transform(df, labels = ordered(labs, labs[order(COUNT_OF_COMPANIES)]))

barplot(COUNT_OF_COMPANIES~labels, new_df,  xlab='TYPES_OF_COMPANIES', 
        ylab='TYPE_OF_COMPANY', 
        main='Number of Different Types of Companies in the database')

【讨论】:

  • 艾伦,感谢您做出有意义的改进。我可以看到您成功运行了代码。但是,当我运行它时,R 给出了一个错误,即 Error in mean(width) : object 'new_df' not found 有什么建议吗?
【解决方案2】:

这对你有用吗?

barplot(sort(counts$COUNT_OF_COMPANIES),  
        xlab = 'TYPES_OF_COMPANIES', ylab = 'Count', ylim = c(0, 1200),
        names.arg =  c("AIM", "Charity", "I-P", "L-P", 
                    "L-G", "LLP", "L-LSE", "NCA", 
                    "PLC", "P-UL", "RC", "UL")[order(counts$COUNT_OF_COMPANIES)],
        main = 'Number of Different Types of Companies in the database')

【讨论】:

  • 谢谢您,这很好,只是我希望数据按升序排序
  • @Ahson 没问题 - 请参阅我的更新。请查看here 以获取有关当有人回答您的问题时该怎么做的建议。谢谢。
猜你喜欢
  • 2017-10-24
  • 1970-01-01
  • 2020-08-13
  • 2020-01-09
  • 1970-01-01
  • 2020-08-23
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多