This question already has answers here:
Order Bars in ggplot2 bar graph
(16 answers)
Closed 3 years ago.
I am attempting to build a chart for some LDA scores I have generated from bacterial abundances.
Here an example of the data:
Taxa <- c('Bacilli', 'Firmicutes', 'Slackia', 'Clostridium')
Level <- c('Class', 'Phylum', 'Genus', 'Genus')
Status <- c('Patient', 'Patient', 'Control', 'Control')
LDA.score <- c(3.5,2.0,-1,-3)
Example <- data.frame(Taxa, Level, Status, LDA.score)
I use this code to make the chart:
ggplot(data=Example, aes(x=Taxa, y=LDA.score, fill=Status)) + geom_bar(stat="identity", position="identity") + coord_flip()
I'd like the bars to be in numerical order so that the bars are grouped into control and patient. However, the resulting bar chart is in alphabetical order according to the x axis.
I have attempted to use reorder() but this doesn't seem to work.
Any help would be appreciated.
We could convert the 'Taxa' to factor based on the order of 'LDA.score' and then use that in ggplot
library(dplyr)
library(ggplot2)
Example %>%
mutate(Taxa = factor(Taxa, levels = as.character(Taxa)[order(LDA.score)])) %>%
ggplot(., aes(x=Taxa, y=LDA.score, fill=Status)) +
geom_bar(stat="identity", position="identity") +
coord_flip()
-output
Related
This question already has an answer here:
How to plot a boxplot with correctly spaced continuous x-axis values in ggplot2
(1 answer)
Closed 3 years ago.
I'd like to do a plot with R ggplot2 functions to highlight relations between a categorical X and a continuous Y variable. But my categorical variable is quantitative (e.g integers) and I would like my plots to respect the position suggested by the quantitative value of X.
Imagine the following dataset:
library(tidyverse)
df <- data.frame(Category=sample(c(1, 2, 5), 1000, replace = T)) %>%
mutate(Value=Category+rnorm(1000))
The easiest boxplot would be :
ggplot(df, aes(x=as.factor(Category), y=Value)) +
geom_boxplot() +
labs(x="Category")
But what I would like is :
add_row(df, Category=3:4, Value=NA) %>%
ggplot(aes(x=as.factor(Category), y=Value)) +
geom_boxplot() +
labs(x="Category")
Do you know any proper way to achieve that beyond the ugly trick above that is not really scalable? Because we can imagine many boxplots. Or even the case in which my categories are decimal values (with of course a limited number of categories). All in all, my wish is to be able to distribute my boxplots along the x-axis according to the quantitative value of the categories. The same question could apply to barplot instead of boxplots of course...
Thanks a lot!
As mentioned by #camille, you should write:
ggplot(df, aes(x=Category, y=Value, group = Category)) +
geom_boxplot() +
labs(x="Category")
This question already has answers here:
Order Bars in ggplot2 bar graph
(16 answers)
Closed 3 years ago.
I have the following dataset:
a<-data.frame(time=c("before","after","before","after"),
company=c(1,1,2,2),
value=c(3.751522,4.776224,3.838707,2.644144 ))
And to plot a graph I used the following code
a$company<-as.factor(a$company)
ggplot(a, aes(x=company, y=value, fill=time)) + geom_col(position="dodge")
As a result, I have the figure for two companies with after and before bars. However, how to fix a problem that the first bar of the company corresponds to the before and next to the after, and not vica versa as in my graph?
Does this achieve what you want:
a<-data.frame(time=factor(c("before","after","before","after"),
levels = c("before", "after")),
company=c(1,1,2,2),
value=c(3.751522,4.776224,3.838707,2.644144 ))
a$company<-as.factor(a$company)
ggplot(a, aes(x=company, y=value, fill=time)) + geom_col(position="dodge")
This question already has answers here:
How can I remove empty factors from ggplot2 facets?
(2 answers)
Closed 4 years ago.
I need to display a faceted bar plot for the count of levels in all the columns of the dataset.
the code,
aas <- sapply(AAA, is.factor)
aas1 <- AAA[,aas]
overview of aas1 dataset
aas2 <- data.frame(t(aas1))
aas2 <- cbind(names = rownames(aas2), aas2)
library(reshape2)
aas3 <- melt(aas2,id = "names")
aas3$variable <- 1
aas3$value <- as.factor(aas3$value)
aas4 <- aggregate(.~ names + value, aas3, sum)
overview of aas4 dataset
ggplot(aas4, aes(x=factor(value), y= variable)) +
geom_bar(stat="identity") + facet_grid(.~names) +
scale_fill_discrete(name="value") + xlab("")
facet bar plot
when i use aas4 dataset for faceted bar plot, each facet is consisting of all levels of "value", but i only need facets with levels corresponding to the variable "names"
Please suggest any better way to plot counts of levels of all factor variables in the dataset.
You need to specify that you want scales="free_x" and, in order not to have the same space for each facet, space="free".
+ facet_grid(.~names, scales="free_x", space="free_x")
This question already has an answer here:
How to add custom labels from a dataset on top of bars using ggplot/geom_bar in R?
(1 answer)
Closed 6 years ago.
I am plotting a simple barplot in ggplot2 and I need to show, over each bar of the plot, something (a number, or a string..) which is not related to this dataset I'm using.
For example with the following instructions:
ggplot(diamonds,aes(cut))+geom_bar()
I get this graph:
And I want to show, over the bars, the elements of the array:
val<-c(10,20,30,40,50)
Obtaining a result like this other graph
I tried using geom_text in this way:
ggplot(diamonds,aes(cut))+geom_bar()+
geom_text(aes(label=val))
But I get the following error message
Error: Aesthetics must be either length 1 or the same as the data (53940): label, x
The problem is that you are making a histogram with geom_bar and there is no y variable specified. In order to apply this example, you need to summarise the cut variable first:
val<-c(10,20,30,40,50)
library(dplyr)
diamonds %>%
group_by(cut) %>%
tally() %>%
ggplot(., aes(x = cut, y = n)) +
geom_bar(stat = "identity") +
geom_text(aes(label = val), vjust = -0.5, position = position_dodge(0.9))
which gives you:
This question already has answers here:
Plot multiple columns on the same graph in R [duplicate]
(4 answers)
Closed 4 years ago.
I need to plot three values, to make three bars for each value of the X-Axis. My data is:
In the X-Axis must be the column labeled as "m" and for each "m" value I need to plot the correspondent "x","y" and "z" value.
I want to use ggplot2 and I need something like this:
I created my own dataset to demonstrate how to do it:
Data:
x <- runif(12,1,1.5)
y <- runif(12,1,1.5)
z <- runif(12,1,1.5)
m <- letters[1:12]
df <- data.frame(x,y,z,m)
Solution:
#first of all you need to melt your data.frame
library(reshape2)
#when you melt essentially you create only one column with the value
#and one column with the variable i.e. your x,y,z
df <- melt(df, id.vars='m')
#ggplot it. x axis will be m, y will be the value and fill will be
#essentially your x,y,z
library(ggplot2)
ggplot(df, aes(x=m, y=value, fill=variable)) + geom_bar(stat='identity')
Output:
If you want the bars one next to the other you need to specify the dodge position at geom_bar i.e.:
ggplot(df, aes(x=m, y=value, fill=variable)) +
geom_bar(stat='identity', position='dodge')