r - 在 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")
我试图找到另一种显示方式,但我什么也没找到。另一种方法是将所有条形的颜色更改为灰色,但随后它们变得无法区分。有谁知道如何解决这个问题?提前谢谢了..
解决方案
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()
.
希望这能让你开始。祝你好运!
推荐阅读
- matlab - MATLAB 中的谢尔宾斯基三角形
- spring-jdbc - JdbcTemplate 对多个表同时批量更新
- php - Laravel 中所有控制器的通用文件上传
- html - django使用html模板将数据插入数据库
- python - 像“The LJ Speech Dataset”这样的数据集
- python - 为了使用 Python 从 Rust 程序内部调用函数,最佳实践是什么?
- verilog - JK 触发器状态图实现的错误输出
- kubernetes - 如何查看上下文的完整详细信息(如令牌)
- java - 无法获取端口上的服务详细信息?
- c# - 无法在 IIS 服务器和客户端上启动 Web 应用程序