R语言直方图的绘制、直方图、多种数据格式怎么区别绘制、图形的修饰美化,颜色反向改变

关注公众号“R医学”获取更多图形绘制代码教程

晓晓
2023-07-17
##直方图

#加载ggplot2函数包
#install.packages("ggplot2")
library(ggplot2)

#创建一个数据
data <- data.frame(
  name=c("A","B","C","D","E") ,  
  value=c(3,12,5,18,45)
)

#数据格式
data
##   name value
## 1    A     3
## 2    B    12
## 3    C     5
## 4    D    18
## 5    E    45
#基本画图(最基本的条形图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
##    cyl
## 1    B
## 2    B
## 3    A
## 4    B
## 5    C
## 6    B
## 7    C
## 8    A
## 9    A
## 10   B
## 11   B
## 12   C
## 13   C
## 14   C
## 15   C
## 16   C
## 17   C
## 18   A
## 19   A
## 20   A
## 21   A
## 22   C
## 23   C
## 24   C
## 25   C
## 26   A
## 27   A
## 28   A
## 29   C
## 30   B
## 31   C
## 32   A
# 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")

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值