※ 引述《Schematic (小小宝的妈)》之铭言:
: [问题类型]:
:
: 程式咨询(我想用R 做某件事情,但是我不知道要怎么用R 写出来)
:
: [软件熟悉度]:
: 入门(写过其他程式,只是对语法不熟悉)
: [问题叙述]:
: 需要将从数据库取出的资料画成柱状图或曲线图
: 从数据库中取出的格式如下
: 年度 性别 人数
: 100 1 33
: 100 2 40
: 101 1 50
: 101 2 49
: 102 1 30
: 102 2 34
: 103 1 43
: 103 2 50
: 预期图片的X轴为每一年度,Y轴为人数;每一年度中又分性别1为一柱状,
: 性别2为另一条。
: 请问有直接的函数可以做出这样的需求吗?
: 若想将上述的格式改为
: 年度
: 性别 100 101 102 103
: 1 33 50 30 43
: 2 40 49 34 50
: 请问要怎么做比较好呢?
: 谢谢
library(tidyr)
library(magrittr)
data_df = read.table(textConnection("
年度 性别 人数
100 1 33
100 2 40
101 1 50
101 2 49
102 1 30
102 2 34
103 1 43
103 2 50"), header = TRUE)
data_df %>% spread(年度, 人数)
# 性别 100 101 102 103
# 1 1 33 50 30 43
# 2 2 40 49 34 50
library(dplyr)
library(ggplot2)
data_df %>% mutate(性别 = factor(性别)) %>%
ggplot(aes(x = 年度, y = 人数, fill = 性别)) %>%
add(geom_bar(stat = "identity", position = "dodge"))
http://i.imgur.com/8pqz7kx.png
PS: dplyr版本要0.4.3才能用中文字段名称输入