在 barplot() 中更改大小、颜色和顺序

Changing size,colors and order in barplot()

这是我正在使用的data_frame

> Social_Split
           V1
Facebook  220
Instagram 213
Linkedin   73
None        3
Quora      44
Reddit    116
Signal     10
Snapchat  104
TikTok     88
Twitter   129

您可以使用此代码重现它:

Social_Split <- structure(list(V1 = 
c(220L, 213L, 73L, 3L, 44L, 116L, 10L, 104L,88L, 129L)), class = "data.frame", 
row.names = c("Facebook","Instagram",
 "Linkedin", "None", "Quora", "Reddit", "Signal",  "Snapchat", "TikTok", "Twitter"))

现在我绘制了这个条形图

social_colors=c("#9bf6ff","#fdffb6","#bdb2ff","#ffc6ff","#b5e48c"
,"#f07167","#9a8c98","#01497c","#f28482","#84a59d")
par(mar=c(4,5,1,1))
barplot(t(Social_Split),horiz = TRUE,las = 1,col=social_colors)

但我有几个问题

  1. 颜色不变
  2. 如果可能,我想重新订购垃圾箱
  3. 如果可能的话,我想让它们更薄

我想要的示例(减去订单):

如果无法使用 barplot() 进行操作,那么我不介意 ggplot() 解决方案,只要我得到相同的结果

这是 ggplot2 的解决方案:

  1. 第一列的行名 tibble::rownames_to_column
  2. fct_reorderforcats 包订购您的数据
  3. 使用 ggplot 绘图,将 width 更改为首选等....

library(tidyverse)

social_colors=c("#9bf6ff","#fdffb6","#bdb2ff","#ffc6ff","#b5e48c"
                ,"#f07167","#9a8c98","#01497c","#f28482","#84a59d")

df <- tibble::rownames_to_column(Social_Split, "Names") %>% 
  mutate(Names = fct_reorder(Names, V1)) 

ggplot(df, aes(x=Names,y=V1, fill = social_colors)) + 
  geom_col(width = 0.3)+
  coord_flip() +
  theme_classic() +
  labs(title = "Number of users per Social Media") +
  theme(legend.position = "none")

使用基本的 R 箱线图功能,您可以通过一些小的调整来实现它。下面的更改将使用您指定的颜色对数据进行排序:

Social_Split <- structure(list(V1 = c(220L, 213L, 73L, 3L, 44L, 116L, 10L, 104L,88L, 129L)), class = "data.frame", 
                          row.names = c("Facebook","Instagram","Linkedin", "None", "Quora", "Reddit", "Signal",  "Snapchat", "TikTok", "Twitter"))
class(Social_Split)
str(Social_Split)

Social_Split <- Social_Split[order(Social_Split$V1),,drop=FALSE]

par(mar=c(4,5,1,1))
barplot(sort(t(Social_Split)),horiz = TRUE, las = 1, col=social_colors, names.arg = row.names(Social_Split), main = "Number of users per Social Media")

最终结果会是这样