按性别划分的垂直条形图

问题描述 投票:0回答:2

我试图通过创建按性别分隔的垂直条形图来表示我的数据。

理想情况下,我希望情节是垂直的,男性和女性具有相同的轴,就像这个例子一样:

Text

我尝试不同的

geom_bar
geom_histogram
,但我无法拥有相同的轴...... 但我不明白我在 x 或 y 中添加哪个值...... 我没有负面数据,而不是“指甲油”等,我有 M1、M2 ..,每个数据有 5 个重复。

r bar-chart data-representation
2个回答
0
投票

类似这样的:

## dummy data
dummy.df <- data.frame(Nail.Polish = c(6000, 500),
                       Rouge = c(3000, 1500),
                       Soap = c(7000, 3500),
                       Sex = c("F", "M"))

library(reshape2)
## transform the data.frame into a format for ggplot
dummy.melt <- melt(dummy.df, id.vars = "Sex")
colnames(dummy.melt) <- c("Sex", "Cosmetic", "Value")

## convert one side to negative numbers
dummy.melt$Value[dummy.melt$Sex=="M"] <- 
  dummy.melt$Value[dummy.melt$Sex=="M"] * -1

library(ggplot2)

## set up the initial plot
g <- ggplot(dummy.melt,
       mapping = aes(x = Cosmetic, y = Value, fill = Sex)) +
  geom_bar(stat = "identity") +
  scale_y_continuous(labels = abs, limits = c(-7500, 7500)) ## using abs() function to convert the scales

## flip the coordinates to make it vertical, add colours, theming etc.
g + coord_flip() +
  scale_fill_manual(values = c("orange", "purple")) +
  theme_bw() +
  theme(panel.grid = element_blank(), aspect.ratio = 1.5)

enter image description here


0
投票

这是一种方法:

library(dplyr)
library(ggplot2)

df <- data.frame(sex = c("M", "M", "M", "M", "F", "F", "F", "F"),
           type = c("M1", "M1", "M2", "M2", "M1", "M1", "M2", "M2"),
           value = c(6,7,5,5,4,6,4,4))

df %>%
  mutate(value = if_else(sex == "M", -value, value)) %>%
  ggplot(aes(x = value, y = type, fill = sex)) + geom_bar(stat = "summary", fun.data = "mean_se") +
  scale_x_continuous(labels = abs)

这个想法基本上是将男性的所有值转换为负数,通过

mutate()
实现,您可以像平常一样生成条形图。因为您希望它是水平的,所以将离散类别放在 y 轴上,将连续值放在 X 轴上,由
aes()
设置,最后使用
scale_x_continuous(labels = abs)
将所有轴标签设置为其自身的绝对值。

© www.soinside.com 2019 - 2024. All rights reserved.