1

我在 R 中创建图时遇到了麻烦。如果我有类似的数据

在此处输入图像描述

我想创建:

在此处输入图像描述

x 轴为 Sepal.length、Sepal.Width、Petal.Width、Petal.Length ,y 轴为不同的物种,高度为值。并根据 y 轴用不同的颜色填充每个条形图。

谢谢!

到目前为止,我已经尝试过:

iris_mean <- aggregate(iris[,1:4], by=list(Species=iris$Species), FUN=mean) 
library(reshape2)
df_mean <- melt(iris_mean, id.vars=c("Species"), variable.name = "Samples", 
  value.name="Values")

ggplot(df_mean,aes(Samples,Values))+
geom_bar(aes(fill=Species),stat="identity")+
  facet_grid(Species~.,scale='free',space='free')+theme(panel.margin = unit(0.1, "lines"))


ggplot(df_mean,aes(x=Samples,y=Species,height =Values))+
  geom_density_ridges2(aes(fill=Species),stat='identity',
                       scale=1.5,
                       alpha=0.1,
                       lty = 1.1)
4

2 回答 2

3

你的多面情节是在正确的轨道上。就像我在评论中所说的那样,您正在尝试显示值的分布,而不是值的手段。您可以手动设置中断并计算计数以显示在 a 中geom_bar,但这很容易变得非常复杂,特别是因为不同类型的度量在不同的尺度上。我建议只使用简单的直方图。我使用gather而不是melt制作长数据——这只是偏好。

除了你所拥有的,这是一个问题 1. 使用发行版,2. 巧妙地处理主题。如果您移动刻面标签,旋转左侧条带,取出条带背景,并删除面板之间的垂直间距,您基本上得到了一个脊图。我不是很熟悉ggridges,但我猜它会做类似的事情。从这里,您可以调整您认为合适的方式。

library(tidyverse)

iris_long <- as_tibble(iris) %>%
  gather(key = measure, value = value, -Species)

ggplot(iris_long, aes(x = value, fill = Species)) +
  # geom_density_ridges() +
  geom_histogram(show.legend = F) +
  scale_y_continuous(breaks = NULL) +
  labs(x = "Measure", y = "Species") +
  facet_grid(Species ~ measure, scales = "free", switch = "both") +
  theme(strip.background = element_blank(), strip.text.y = element_text(angle = 180), 
        strip.placement = "outside", panel.spacing.y = unit(0, "cm"))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

reprex 包(v0.2.0)于 2018 年 7 月 19 日创建。

于 2018-07-19T15:00:02.170 回答
1

仅供参考,最好发布您的数据而不是屏幕截图,并且您还应该发布您迄今为止尝试过的代码。

您正在寻找的是facet_grid

library(tidyverse)

iris_summarized <- iris %>%
 group_by(Species, Sepal.Length) %>%
 summarize(total = n())

ggplot(iris_summarized, aes(x = Sepal.Length, y = total, fill = Species)) + # the fill argument sets the color for the bars
 geom_col() + # use geom_col instead of geom_bar if you are explicitly referencing counts in your data set
 facet_grid(Species ~ ., switch = "y") + # the switch = "y" argument moves the species name to the left side of the graph
 theme(strip.placement = "outside", # this moves the title of each facet to the left of the axis
       strip.background = element_blank()) # this makes the title of each facet not have a background
于 2018-07-19T14:22:22.770 回答