ggplot多组柱状图标记数值

iris1<-melt(iris, id.vars='Species', measure.vars=c('Sepal.Length','Sepal.Width','Petal.Length','Petal.Width'))

iris1<-data.table(iris1)

iris1_1<-iris1[,list(sumvalue=sum(value)),by=list(Species,variable)]

setorder(iris1_1,Species)

#设置标签的高度,累计的高度为堆叠上面的一半

iris1_2<-iris1_1[,label_y:=cumsum(sumvalue)-sumvalue/2,by=list(Species)]

ggplot(iris1_2,aes(x=factor(Species, levels=levels(iris1_2$Species)[c(3,2,1)]), y=sumvalue, fill=factor(variable,levels=levels(iris1_2$variable)[c(4,3,2,1)])))+

geom_bar(stat='identity',position=position_dodge())+ #本来不用reverse是从上到下,反过来

theme1+

geom_text(aes(x=Species,y=sumvalue+20,label=sumvalue, color=factor(variable, levels=levels(iris1_2$variable)[c(4,3,2,1)])),#和fill的一致

position=position_dodge(width=0.9),show.legend = F)+#showlegend 隐藏文字的图例

ggtitle('柱状图')+

scale_fill_discrete(name='图例', #图例项(或者用scale_fill_discrete)

labels=levels(iris1_2$variable)[c(4,3,2,1)])+

#颜色 scale_x_discrete(name='类别', #x轴坐标名称

labels=levels(iris1_2$Species)[c(3,2,1)])+ #离散的标签

scale_y_continuous(name='值', #y轴坐标名称

breaks=seq(0,400,50),limits=c(0,400))#连续的标签和坐标轴


ggplot2 是 R 语言中非常流行的数据可视化库,它基于层叠(layering)的概念,使得创建复杂的统计图形变得直观且灵活。分组柱状图(grouped bar chart)是 ggplot2 中常用的一种图表类型,用于展示不同类别(通常是分类变量)下的数据分布或比较。 在 ggplot2 中,要创建分组柱状图,你需要按照以下步骤操作: 1. 加载 ggplot2 库:首先确保已经安装了 `ggplot2`,然后使用 `library(ggplot2)` 加载。 2. 数据准备:确保你的数据集有一个分类变量(通常列名为 "x" 或 "category")和一个数值变量(通常列名为 "y" 或 "value"),用于表示每个类别的数量或比例。 3. 创建数据框:数据应该被组织成一个数据框(data frame),方便 ggplot2 访问。 4. 基本语法:使用 `ggplot()` 函数创建一个新的图形,然后添加数据 `data = your_data`,指定 x 变量和 y 变量。 ```R ggplot(data, aes(x = category, y = value)) + geom_bar(stat = "identity", fill = "your_color") # 使用geom_bar绘制柱状图 ``` 5. 添加分组:如果你有多组数据想要对比,可以在 `aes()` 中添加 `group` 参数,如 `group = group_variable`。 6. 定义标题、轴标签等:使用 `labs()` 函数设置标题、x 轴和 y 轴标签。 7. 渲染图例:如果需要,使用 `scale_fill_manual()` 或 `scale_color_manual()` 来添加或调整图例。 ```R ggplot(data, aes(x = category, y = value, fill = group_variable)) + geom_bar(stat = "identity") + labs(title = "Grouped Bar Chart", x = "Category", y = "Value") + scale_fill_manual(values = c("your_group_1_color", "your_group_2_color")) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值