首页 > 解决方案 > 在 R 中重新格式化条形图

问题描述

对于一项任务,我需要可视化公司的市场价值,这些公司分成不同的组来指示行业。我创建了以下图表:股票市场价值图表,但这些图表在学术文章中不允许使用这种颜色。使用的代码如下:

ggplot(data = g, aes(x=g$MarketCap, group = g$SIC, fill=SIC)) +
  geom_histogram(position = "dodge", binwidth = 1000) + theme_bw() + xlim(0,5000) +
  labs(x = "Market Value (in Millions $)", title = "Market Value per Industry")

我试图找到另一种显示方式,但我什么也没找到。另一种方法是将所有条形的颜色更改为灰色,但随后它们变得无法区分。有谁知道如何解决这个问题?提前谢谢了..

标签: rggplot2data-visualizationbar-chart

解决方案


Patubd,有很多事情要做,恐怕这些评论不足以让你继续前进。因此,我在这里尝试指出一些事情。

您没有提供可重现的示例。因此,我预先“模拟”了一些数据。您可以根据自己的喜好进行调整。

在您的ggplot()通话中,您指的是g数据框。然后不需要使用显式g$variable表示法。

你在你的MeanMarketCap管道中做同样的事情。我想这是你面临的问题的一部分。

数据:

library(dplyr)
set.seed(666)   # set seed for random generator
# ------------------- data frame with 60 examples of industry group SIC and MarketCap
df <- data.frame(
   SIC        = rep(c("0","1","2"), 20)
  , MarketCap = c(rep(50, 30), rep(1000, 15), rep(2000, 10), rep(3000, 5))
)
# ------------------- add 15 random picks to make it less homogenuous
df <- df %>% 
   bind_rows(df %>% sample_n(15))

(I) “色彩较少”和/或方面

fig1 <- ggplot(data = df, aes(x=MarketCap, group = SIC, fill=SIC)) +
    geom_histogram(position = "dodge") + 
#------------- as proposed to make graph less colourful / shades of grey ---------
    scale_fill_grey() + 
#---------------------------------------------------------------------------------
    theme_bw() + xlim(0,5000) +
    labs(x = "Market Value (in Millions $)", title = "Market Value per Industry")


# make a 2nd plot by facetting above
# If the plot is stored in an object, i.e. fig1, you do not have to "repeat" the code
# and just add the facet-layer
fig2 <- fig1 + facet_grid(. ~ SIC)

library(patchwork)   # cool package to combine plots
fig1 / fig2          # puts one plot above the other

通过一个方面,您可以拆分组。这支持并排分析......并且组的颜色不太重要,因为这现在是刻面的一部分。但是您可以将两者结合起来,如图所示。

在此处输入图像描述

(二)汇总均值

如果您不使用该df$variable符号,您的代码将起作用。这会破坏 group-by 调用,您可以参考完整的数据框。

df %>% 
   group_by(SIC) %>% 
   summarise(MeanMarketCap = mean(MarketCap))

这产生了 - 简单的模拟 - 数据:

# A tibble: 3 x 2
  SIC   MeanMarketCap
  <chr>         <dbl>
1 0              858.
2 1              876.
3 2              858.

要显示分布,可以使用箱线图。箱线图适用于四分位数间距(第 25-75 个百分位数和中位数 [第 50 个百分位数]。
您可以使用geom_boxplot()它。ggplot将负责统计计算。

df %>%
   ggplot() +
   geom_boxplot(aes(x = SIC, y = MarketCap)

使用您的数据(更多不同的数据点),该图看起来会更令人印象深刻。但是您已经可以清楚地看到示例行业 SIC 的中位数差异。

在此处输入图像描述

如果您觉得可以使用geom_jitter().

希望这能让你开始。祝你好运!


推荐阅读