Reputation: 222
I have a data.frame
with a single record and a N numeric columns.
I would like to graph in R
as a barplot of all columns having non-zero value on the same graph in ggplot
.
For example:
df <- data.frame(a=1, b=0, c=10, d=20)
I transposed the data.frame
but didn't manage to name both columns.
Note: Python implements the same graph though sns
:
sns.barplot(x = 'Name', y = 'count', data*)
Upvotes: 2
Views: 433
Reputation: 16178
For doing bar plot, you can use tidyr
to pivot your data into a longer format compatible with ggplot and filter
to remove zero values:
library(tidyverse)
library(ggplot2)
df=data.frame(a=1, b=0, c=10, d=20)
df %>% pivot_longer(everything(), names_to = "Variable", values_to = "Values") %>% filter(., Values != 0)
# A tibble: 3 x 2
Variable Values
<chr> <dbl>
1 a 1
2 c 10
3 d 20
And if you are combining it with ggplot
, it gives you:
df %>% pivot_longer(everything(), names_to = "Variable", values_to = "Values") %>% filter(., Values != 0) %>%
ggplot(., aes(x = Variable, y = Values, fill= Variable))+
geom_bar(stat = "identity")
Upvotes: 4
Reputation: 76402
In base R this is as easy as
barplot(unlist(df[1, df[1, ] != 0]))
If you prefer ggplot2
graphics,
library(tidyverse)
df %>%
gather(key, value) %>%
filter(value != 0) %>%
ggplot(aes(x = key, y = value)) +
geom_col()
Upvotes: 6