按类别划分的水平条形图
我有以下数据框
A <- c(2020, 2020, 2020, 2021, 2021, 2021)
B <- c("category 1", "category 2", "category 3", "category 1", "category 2", "category 3")
C <- c(7, 10, 5, 11, 8, 7)
data <- data.frame(A, B, C)
names(data) <- c("yeat", "categories", "value")
如何绘制水平条形图,如下所示(即类别按每年的值排序):
I have the following data frame
A <- c(2020, 2020, 2020, 2021, 2021, 2021)
B <- c("category 1", "category 2", "category 3", "category 1", "category 2", "category 3")
C <- c(7, 10, 5, 11, 8, 7)
data <- data.frame(A, B, C)
names(data) <- c("yeat", "categories", "value")
How can I plot a horizontal bar chart, that will look like this (i.e., the categories are sorted by their values for each year):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
lapply
中使用barplot
。按年份
分割
数据,并根据顺序
绘制值
。我们还根据此方案给出条形col=
ors 以及使用mtext
的标签。颜色和标签可以方便地存储在矩阵
m
中,其中行名称按类别排列,我们稍后可以轻松匹配。数据:
Use
barplot
in anlapply
.split
the data byyear
and plot thevalue
s according to theirorder
. We also give the barscol=
ors according to this scheme as well as labels usingmtext
.Colors and labels may be conveniently stored in a matrix
m
with row names by categories that we can easily match later.Data:
您可以使用以下代码:
输出:
You can use this code:
Output:
使用 r-plotly 作为绘图库怎么样?
示例输出:

自定义颜色的定义是从这个答案中无耻地窃取的。
How about using r-plotly as the plotting library?
Sample output:

The definitions of the custom colors are shamelessly stolen from this answer.