简体   繁体   English

如何在R中按类别绘制包含计数的表?

[英]How to plot a table containing counts by class in R?

How do you visulize in R this kind of table, where x is the class and y the number of occurences in the class?你如何在 R 中可视化这种表,其中 x 是类,y 是类中出现的次数? I want to visualize the distribution but all I manage to do is a barplot (putting y into a vector), so it doesn't use the info of x.我想可视化分布,但我设法做的只是一个条形图(将 y 放入向量中),因此它不使用 x 的信息。 I can add the tags afterwards but is there a better way to proceed and directly use this kind of format.我可以在之后添加标签,但有没有更好的方法来继续并直接使用这种格式。 Plus, if I have thousands of class, how can I just plot them with larger bins that the one in the table?另外,如果我有数千个班级,我怎么能用比表中更大的箱子来绘制它们呢? (example here this could be plotting just two class <50 and >50). (这里的例子可能只是绘制两个 <50 和 >50 的类)。

x   y
100 1954
90  106
80  700
70  27
60  861
50  32
40  5491
30  936
20  7364
10  408

You may use barplot您可以使用barplot

barplot(y~x, df)

Or in ggplot2或者在ggplot2

library(ggplot2)
ggplot(df, aes(x, y)) + geom_col()

If you need only two categories, you can create new column and then use aggregate .如果您只需要两个类别,您可以创建新列,然后使用aggregate

df$class <- ifelse(df$x > 50, 'less than 50', 'higher than 50')
barplot(y~class, aggregate(y~class, df, sum))

Following @Ronak Shah said, you can make graph.按照@Ronak Shah 的说法,您可以制作图表。 For many classes, you may use cut .对于许多类,您可以使用cut For example, split your data as >50 and <50,例如,将您的数据拆分为 >50 和 <50,

df %>%
  mutate(grp = cut(V1,2)) %>%
  ggplot(aes(grp, V2)) + geom_col()

will make bar graph.将制作条形图。 在此处输入图片说明

If your first column is a factor in your data, you might need to add as.numeric(first column) before that.如果您的第一列是数据中的一个因素,您可能需要在此之前添加as.numeric(first column)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM