仅绘制与 R 中的条件匹配的特定数据帧行

Plot only specific dataframe rows that matches a criteria in R

我有一个这样构建的数据框:

       Id        Client           data     
        1           5             25     
        2           8             63       
        3          13             42
        4           5             87
        5           8             35

和一个数组:clients <- c(5,8)

我需要为“客户”数组中的每个客户绘制不同的直方图(数据列的)。在这个例子中,我将为客户 5 绘制直方图,其中包含两个条 (25,87),为客户 8 绘制一个也包含两个条 (63,35) 的直方图。我认为我需要使用 facet_wrap 函数为每个客户绘制直方图,我还尝试为每个客户做一些类似的事情,但没有成功。我不确定我该怎么做,所以任何帮助都会很棒!

看来您只是没有进行足够的数据整理。此外,根据您的描述,您需要 barplot,而不是直方图(它会报告数据中特定值的计数,而不是它们的值)。

这是 base 中的解决方案。

dt = data.frame("id" = 1:5, "client" = c(5,8,13,5,8), "data"=c(25,63,42,87,35))
clients = c(5,8,13) # for particular clients, or unique(dt$client) for all clients

# get data for every client
lst = lapply(clients, function(x){dt[dt$client == x, "data"]})

# unify length and transform into a matrix
len = max(sapply(lst, length))
mat = do.call(cbind, lapply(lst, "[", seq_len(len)))

# Put some nice legend
colnames(mat) = paste("Client", clients)

# plot this matrix with barplot
barplot(mat, beside=TRUE, las=1)

如果数量有限clients,您可以在同一张图上绘制。

library(dplyr)
library(ggplot2)

df %>%
  filter(Client %in% clients) %>%
  group_by(Client) %>%
  mutate(Id = factor(row_number())) %>%
  ggplot() + aes(Client, data, fill = Id) + 
  geom_bar(stat = 'identity', position = 'dodge')

有小平面:

df %>%
  filter(Client %in% clients) %>%
  group_by(Client) %>%
  mutate(Id = factor(row_number())) %>%
  ggplot() + aes(Client, data, fill = Id) + 
  geom_bar(stat = 'identity', position = 'dodge') + 
  facet_wrap(~Client, scales = 'free_x')

数据

df <- structure(list(Id = 1:5, Client = c(5L, 8L, 13L, 5L, 8L), data = c(25L, 
63L, 42L, 87L, 35L)), class = "data.frame", row.names = c(NA, -5L))

clients <- c(5,8)