无法在 ggplot2 中使用scale_x_discrete指定x轴:“包含非有限值的行”

发布于 2025-01-11 16:05:29 字数 509 浏览 0 评论 0原文

我想绘制条形图并使用 scale_x_discrete 手动描述条形。 x 变量有 9 个级别,group-变量有 3 个级别。

ggplot(data, aes(x = education, group = food, fill = food)) +
geom_bar() +
scale_x_discrete(limits=c("A","B","C","D","E","F","G","H","I"))

我对另外两个 x 变量做了同样的绘图,效果非常好。这个函数可以在没有 scale_x_discrete 函数的情况下工作,但是当我使用它为条形提供较短的名称时,我会收到以下错误:

警告消息:删除了包含非有限值 (stat_count) 的 979 行。

没有 NA,但对于 x 的某些级别,组变量“食物”只有一个级别,而我绘制的其他变量则不是这种情况,因此这可能是问题的一部分。 有什么解决办法吗?

I want to plot a bar chart and use scale_x_discrete to manually describe the bars. The x variable has 9 levels, the group-variable has 3 levels.

ggplot(data, aes(x = education, group = food, fill = food)) +
geom_bar() +
scale_x_discrete(limits=c("A","B","C","D","E","F","G","H","I"))

I did the same plot with the two other x-variables and it worked perfectly. This one works without the scale_x_discrete function, but as soon as I use it to give shorter names to the bars, I get the following error:

Warning message: Removed 979 rows containing non-finite values (stat_count).

There are no NAs, but for some levels of x there is only one level of the group-variable "food", which isn't the case for the other variables I plotted, so that might be part of the problem.
What could be a solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一袭白衣梦中忆 2025-01-18 16:05:29

示例数据:

education=c("A","B","C","D","E","F","G","H","I")
food=c("Soup","Vegan","Meat","Raw","Soup","Vegan","Meat","Raw", "Vegan" )

data=cbind(education,food)
data<-data.frame(data) # make sure that your data is a df

示例代码:

ggplot(data, aes(x = education, group = food, fill = food)) +
  geom_bar() +
  #scale_x_discrete(limits=c("A","B","C","D","E","F","G","H","I"))+
   scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I"))+
  labs(y="Count", x="Education", fill="Food type")+
  theme_bw()

输出:

在此处输入图像描述

Sample data:

education=c("A","B","C","D","E","F","G","H","I")
food=c("Soup","Vegan","Meat","Raw","Soup","Vegan","Meat","Raw", "Vegan" )

data=cbind(education,food)
data<-data.frame(data) # make sure that your data is a df

Sample code:

ggplot(data, aes(x = education, group = food, fill = food)) +
  geom_bar() +
  #scale_x_discrete(limits=c("A","B","C","D","E","F","G","H","I"))+
   scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I"))+
  labs(y="Count", x="Education", fill="Food type")+
  theme_bw()

Output:

enter image description here

熟人话多 2025-01-18 16:05:29

使用scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I")) (而不是 limits )确实有效。感谢安德斯。谁在上面的评论中发布了这个解决方案。

Using scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I")) (instead of limits ) did work. Thanks to AndS. who posted this solution in a comment above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文