【问题标题】:barchart - count variable is showing frequency instead of values from data column条形图 - 计数变量显示频率而不是数据列中的值
【发布时间】:2018-12-18 00:09:38
【问题描述】:

作为参考,这是我的数据 - here

我正在尝试查看这些变量之间的关系并使用条形图。下面是我正在使用的 R 代码和我得到的绘图。

library(lattice)
barchart(DiagAge~interaction(Gender,Race),groups=Ethnicity,data=df,auto.key=T,stack=T)

here

我想在 Y 轴上查看 DiagAge(诊断出糖尿病的年龄),但是,当前代码显示的数字看起来像是某事的频率。

【问题讨论】:

标签: r data-visualization data-science data-analysis


【解决方案1】:

这是tidyrggplot 解决方案。我使用有代表性的数据来​​节省时间。以后请使用dput(data) 将您的数据添加到您的问题中。这是一个建议的解决方案:您可以根据需要更改颜色和主题。

   library(tidyverse)
df<-data.frame(Gender=c("M","F","M"),Race=c("Non White","White","Non White"),DiagAge=c(13,24,25))
df %>% 
  mutate_if(is.character,as.factor) %>% 
  ggplot(aes(Race,DiagAge,fill=Gender))+
  geom_bar(stat="identity",position="identity",col="black")+
  geom_label(aes(label=DiagAge))

干杯

【讨论】:

  • 非常感谢您的帮助。我在原始问题中包含了我的数据,但是,有人对其进行了编辑。
  • 是的。我得到了一个很好的图表,它在 x 轴上有白人和非白人,在 y 上有年龄,两个条形图中充满了性别。看起来很棒。
  • 另外,我想知道为什么我们使用--- DiagAge=c(13,24,25) ?
  • 没有意义。就像Race 专栏一样,我只是将其用作表示。您可以使用您拥有的任何值来代替它(即用您的数据替换df。这只是为了表示。请随时接受这个答案当且仅当你觉得它有帮助时。
【解决方案2】:

tidyverse 是你的朋友!主要是ggplot2::geom_col


您的代码可能如下所示:

library(tidyverse)

mytbl <- df %>%
  mutate(racegender = paste(Race,Gender)) 

g <- ggplot(mytbl, aes(racegender)) + scale_fill_brewer(palette = "Spectral")

g + geom_col(aes(fill = Ethnicity, y = DiagAge)) +
  labs(title="Your title", 
       subtitle="Your subtitle") +
  theme(axis.text.x = element_text(angle=65, vjust=0.6))

这里我使用diamonds 数据集上的这段代码来说明你的情况。

library(tidyverse)

通过mutate 创建一个cutcolor 变量。在我的示例中,为了简洁起见,我 filter 指定了某些值(很可能对您来说不是必需的或有效的)。

mytbl <- diamonds %>%
  mutate(cutcolor = paste(cut,color)) %>% 
  filter(color %in% c("D", "E", "F"),
         cut %in% c("Fair", "Good", "Very Good"))  # to limit the number of columns

图表将使用mytbl,并在横轴上使用cutcolor

g <- ggplot(mytbl, aes(cutcolor)) + scale_fill_brewer(palette = "Spectral")

主要的ggplot 函数是geom_colfill 堆叠它们,垂直轴是 price(在您的情况下为 DiagAge)。 theme 部分有助于调整水平标签文本的角度。

g + geom_col(aes(fill = clarity, y = price)) +
  labs(title="Bar Graph with Stacked Types", 
       subtitle="Price Across Diamond Cut and Color") +
  theme(axis.text.x = element_text(angle=65, vjust=0.6))angle=65, vjust=0.6))

结果:

【讨论】:

  • 这是一个非常好的表示。谢谢你也向我解释。现在对我来说更有意义了。
猜你喜欢
  • 2016-01-04
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 2021-03-24
  • 2011-02-02
  • 1970-01-01
  • 2022-10-14
  • 2018-05-23
相关资源
最近更新 更多