直方图、柱状图

##直方图

#加载ggplot2函数包

#install.packages("ggplot2")

library(ggplot2)

#创建一个数据

data <- data.frame(

  name=c("A","B","C","D","E") , 

  value=c(3,12,5,18,45)

)

#数据格式

data

#基本画图(最基本的条形图geom_bar)

ggplot(data, aes(x=name, y=value)) +

  geom_bar(stat = "identity")

#图形水平

ggplot(data, aes(x=name, y=value)) +

  geom_bar(stat = "identity") +

  coord_flip()

#图形宽度

ggplot(data, aes(x=name, y=value)) +

  geom_bar(stat = "identity", width=0.2)

#控制颜色

ggplot(data, aes(x=name, y=value, fill=name )) +

  geom_bar(stat = "identity") +

  scale_fill_hue(c = 40) +

  theme(legend.position="none")

#如果每一类没有直接计数好,去掉stat = "identity"即可

mtcars <- as.data.frame(factor(mtcars$cyl,labels=c("A","B","C")))

colnames(mtcars) <- "cyl"

mtcars

# 1

ggplot(mtcars, aes(x=as.factor(cyl))) +

  geom_bar(color="blue", fill=rgb(0.1,0.4,0.5,0.7) )

# 2-使用色相调整填充颜色,`c`参数指定色相的起始值,取值范围为0到360。

ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +

  geom_bar( ) +

  scale_fill_hue(c = 40) +

  theme(legend.position="none")

# 3-使用Brewer调色板填充颜色,`palette`参数指定调色板的名称,可以是"Set1"、"Set2"、"Set3"等

ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +

  geom_bar( ) +

  scale_fill_brewer(palette = "Set3") +

  theme(legend.position="none")

# 4-使用灰度调整填充颜色,`start`参数指定灰度的起始值,取值范围为0到1,`end`参数指定灰度的结束值,取值范围为0到1

ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +

  geom_bar( ) +

  scale_fill_grey(start = 0.25, end = 0.75) +

  theme(legend.position="none")

# 5-手动指定填充颜色,`values`参数指定颜色向量,可以是颜色名称或十六进制颜色代码。在这个例子中,使用了红、绿、蓝三种颜色

ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + 

  geom_bar( ) +

  scale_fill_manual(values = c("red", "green", "blue") ) +

  theme(legend.position="none")


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容