mysql - 从多列创建条形图

标签 mysql sql r plot

我有以下数据集:

Location    Type    FromDate    ToDate  1   2   3   4   5
  A          1        12-Jul    13-Jul  2   4   0   1   2
  A          2        12-Jul    13-Jul  0   0   1   4   1
  B          1        12-Jul    13-Jul  0   1   1   3   1
  B          2        12-Jul    13-Jul  1   0   0   0   1
  C          1        12-Jul    13-Jul  2   3   1   5   0
  C          2        12-Jul    13-Jul  3   3   1   0   0

如何在 R 中为第 1 天到第 5 天的每个位置(包括类型 1 和类型 2)创建条形图?

最佳答案

一个稍微替代的解决方案,它不使用 reshape2plyr,而是使用 dplyrtidyr。后一种组合使用了越来越流行的管道。

首先读取数据:

df <- read.table(header=TRUE, text="Location    Type    FromDate   ToDate 1   2   3   4   5
A          1        12-Jul    13-Jul  2   4   0   1   2
A          2        12-Jul    13-Jul  0   0   1   4   1
B          1        12-Jul    13-Jul  0   1   1   3   1
B          2        12-Jul    13-Jul  1   0   0   0   1
C          1        12-Jul    13-Jul  2   3   1   5   0
C          2        12-Jul    13-Jul  3   3   1   0   0")
# remove the X-es which are put in front of the days
names(df) <- gsub("X","",names(df))

加载所需的库:

library(dplyr)
library(tidyr)
library(ggplot2)

将数据从宽格式融合为长格式:

df.m <- df %>% gather(day,value,5:9)

创建情节:

ggplot(data=df.m, aes(x=day, y=value, fill=as.factor(Type))) + 
  geom_bar(stat="identity", position="dodge") + 
  xlab("Day of the week") +
  scale_fill_discrete("Type\nof\nsomething\n") +
  facet_grid(Location ~ ., labeller=label_both) +
  theme_bw() +
  theme(axis.title.y=element_blank())

结果是: enter image description here

<小时/>

但是,考虑到您的数据,折线图可能是更好的可视化效果:

ggplot(data=df.m, aes(x=day, y=value, color=as.factor(Type), group=as.factor(Type))) + 
  geom_line(size=1.5) + 
  xlab("Days") +
  scale_color_discrete("Type\nof\nsomething\n") +
  facet_grid(Location ~ ., labeller=label_both) +
  theme_bw() +
  theme(axis.title.y=element_blank())

结果是: enter image description here

关于mysql - 从多列创建条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25730912/

相关文章:

android - 如何在Android 6.0应用程序中连接到MySQL

mysql - 为什么这个简单的 MySQL 子查询不起作用?

r - R 中的神经网络 : what are the difference between stepmax and rep parameters?

r - 在 R 中,修改具有单个名称绑定(bind)的对象不应该保留其内存地址吗?

r - ggplot误差线问题

c++ - 无法在我的 ubuntu 中正确安装 MySQL connector/c++

php - 数据库连接错误 : Can't connect to local MySQL server through socket

SQL Server : get average per week for the past 30 weeks

sql - 更改列数据类型时保留SQL索引

mysql - 如何获得链接到第三个表的两个表的总和