简体   繁体   English

如何从R中的计数数据绘制条形图?

[英]How to draw a barplot from counts data in R?

I have a data-frame 'x' 我有一个数据框“ x”

X

I want barplot like this 我想要这样的地势 在此处输入图片说明

I tried 我试过了

barplot(x$Value, names.arg = x$'Categorical variable')
ggplot(as.data.frame(x$Value), aes(x$'Categorical variable')

Nothing seems to work properly. 似乎没有任何正常工作。 In barplot, all axis labels (freq values) are different. 在条形图中,所有轴标签(频率值)都不同。 ggplot is filling all bars to 100%. ggplot将所有条形填充至100%。

You can try plotting using geom_bar(). 您可以尝试使用geom_bar()进行绘图。 Following code generates what you are looking for. 以下代码生成您想要的内容。

df = data.frame(X = c("A","B C","D"),Y = c(23,12,43))
ggplot(df,aes(x=X,y=Y)) + geom_bar(stat='identity') + coord_flip()

You have to use stat = "identity" in geom_bar() . 您必须在geom_bar()使用stat = "identity"

dat <- data.frame("cat" = c("A", "BC", "D"),
                  "val" = c(23, 12, 43))
ggplot(dat, aes(as.factor(cat), val)) +
  geom_bar(stat = "identity") +
coord_flip()

It helps to read the ggplot documentation. 它有助于阅读ggplot文档。 ggplot requires a few things, including data and aes() . ggplot需要一些东西,包括dataaes() You've got both of those statements there but you're not using them correctly. 您已经在这两个语句,但您没有正确使用它们。

library(ggplot2)
set.seed(256)

dat <- 
  data.frame(variable = c("a", "b", "c"), 
             value = rnorm(3, 10))

dat %>%
  ggplot(aes(x = variable, y = value)) +
  geom_bar(stat = "identity", fill = "blue") +
  coord_flip()

Here, I'm piping my dat to ggplot as the data argument and using the names of the x and y variables rather than passing a data$... value. 在这里,我将dat传递给ggplot作为data参数,并使用xy变量的名称,而不是传递data$...值。 Next, I add the geom_bar() statement and I have to use stat = "identity" to tell ggplot to use the actual values in my value rather than trying to plot the count of the number. 接下来,我添加geom_bar()语句,并且我必须使用stat = "identity"来告诉ggplot在我的value使用实际值,而不是尝试绘制数字的计数。

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

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