首页 > 解决方案 > 当 barplot 正确绘制所有内容时,ggplot 将所有数据绘制为单列

问题描述

我的数据是这样的单列:

Number Assigned Row 
1        1
2        1
3        2
4        1
5        2
6        3
...      ...

当我使用 barplot 绘图时,我得到了我想要的:

条形图

然而,当我使用 ggplot + geom_bar 我得到这个:

ggplot + geom_bar

这是我的 ggplot 代码:

  count <- data.frame(alldata[[xaxis]])
  ggplot(data=count, aes(x="My X Axis", y="My Y Axis")) +
  geom_bar(stat="identity")

与我用于条形图的代码相比:

  counts <- table(alldata[[xaxis]])
  barplot(counts,
          main = xaxis,
          xlab = "Percentile",
          cex.names = 0.8,
          col=c("darkblue","red"), beside = group != "NA")

标签: rggplot2bar-chart

解决方案


假设这是您的数据:

df <- data.frame(AssRow = sample(1:3, 100, T, c(0.2, 0.5, 0.3)))
head(df)
#   AssRow
#1      2
#2      1
#3      2
#4      3
#5      2
#6      2

这将为您提供每个分配行计数的条形图,并为它们着色:

ggplot(df, aes(x=AssRow, fill=as.factor(AssRow))) + 
  geom_bar()

要更改标签,请使用xlab ylab/make 背景更漂亮:

ggplot(df, aes(x=AssRow, fill=as.factor(AssRow))) + 
  geom_bar() +
  xlab("My X-label") +
  ylab("My Y label") +
  theme_bw()

输出:

在此处输入图像描述


推荐阅读