[英]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)
我需要为“客户”数组中的每个客户 plot 一个不同的直方图(数据列)。 在这个例子中,我将为客户 5 绘制 plot 直方图,其中包含两个柱状图 (25,87),为客户 8 绘制一个直方图,也包含两个柱状图 (63,35)。 我认为我需要为每个客户使用 facet_wrap function 到 plot 直方图,我也尝试为每个客户做一些类似的事情,但没有奏效。 我不确定我该怎么做,所以任何帮助都会很棒!
好像你只是没有做足够的数据争论。 此外,根据您的描述,您需要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
数量有限,您可以在同一张图中使用 plot。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.