【问题标题】:ggplot plotting all data as a single column when barplot plots everything correctly当 barplot 正确绘制所有内容时,ggplot 将所有数据绘制为单列
【发布时间】:2019-02-12 00:41:39
【问题描述】:

我的数据是这样的单列:

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

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

但是,当我使用 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")

【问题讨论】:

  • 移除 x 和 y 变量周围的 cmets。确保输入的 x 和 y 变量与数据框中的列匹配
  • @RAB “删除 cmets”是什么意思?
  • 您不需要在 x 和 y 变量名周围加上 "。我的意思是引号 - 我的错
  • aes(x, y) 不只是情节的标签吗?那我将如何绘制与计数?因为 Y 应该是病例数。
  • 不,那是 xlab 和 ylab。 aes(x ,y) 是您希望在 x 和 y 列上显示的变量的名称

标签: r ggplot2 bar-chart


【解决方案1】:

说这是你的数据:

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/使背景更漂亮:

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

输出:

【讨论】:

  • 修复了它。我只是在我的 data.frame 函数中缺少 AssRow = sample(...)。
  • 很高兴我能帮上忙 :)
  • 不做什么,我似乎无法重新标记填充(as.factor(AssRow))
  • 在末尾添加+ guides(fill=guide_legend(title="New Legend Title"))
猜你喜欢
  • 2020-12-07
  • 2021-08-26
  • 2018-10-25
  • 2019-08-29
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多