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:
Related
I am trying to make a histogram of percentages for multiple columns of data in one graph. Is there a way to do this without transforming the data into an even longer format? Basically, I want to combine multiple histograms on one plot with the same y axis. I can't get facet_grid and facet_wrap to work because everything is in different columns. Here is some sample data:
data <- data.frame("participant"=c(1,2,3,4,5),
"metric1"=c(0,1,2,0,1),
"metric2"=c(1,2,0,1,2),
"metric3"=c(2,0,1,2,0),
"date"=rep("8/14/2021",5))
Ideally, I would have a stacked bar for metric 1, next to that a stacked bar for metric 2, fianlly a stacked bar for metric 3. I can generate one stacked bar at a time with the following code:
ggplot(data = data,
aes(x = date, group = factor(metric1), fill=factor(metric1))) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent)
How do I combine this graph with the graphs for metric 2 and 3 so that they are all on the same graph with the same axes? Can it be done without making the data long? My real data is more complicated than the test data, and I'd like to avoid transforming it. Thank you for reading and any help you can offer.
Reshape to 'long' format with pivot_longer and create the bar plot
library(dplyr)
library(ggplot2)
library(tidyr)
data %>%
pivot_longer(cols = starts_with('metric'), values_to = 'metric') %>%
ggplot(aes(x = date, group = factor(metric),fill = factor(metric))) +
geom_bar() +
facet_wrap(~ name)
This question already has answers here:
Change bar plot colour in geom_bar with ggplot2 in r
(2 answers)
Closed 2 years ago.
I used the code below but it only shows charts with no color
gbar <- ggplot(data=episode_data, aes(x=season))
gbar +
geom_bar() +
scale_fill_brewer(type = "seq", palette = 1, direction = 1, aesthetics = "fill")
As no data is provided, I will explain you two way to add color in a plot using demo data iris. You can set the aesthetic element fill in order to add some variable to fill your bars. The output of a code using that option would be next:
library(ggplot2)
library(tidyverse)
#Data
data("iris")
#Example 1 color by species
iris %>% pivot_longer(-Species) %>%
ggplot(aes(x=name,y=value,fill=Species))+
geom_bar(stat='identity')
Output:
The second option would be directly enable fill option inside geom_bar() with some defined color like this:
#Examples 2 only one color
iris %>% pivot_longer(-Species) %>%
ggplot(aes(x=name,y=value))+
geom_bar(stat='identity',fill='cyan3')
Output:
For the code you added try this, and next time please include a sample of your data to reproduce your issue:
#Option 1
ggplot(data=episode_data, aes(x=season))+
geom_bar(stat='identity',fill='red')
#Option 2
ggplot(data=episode_data, aes(x=season,fill=factor(season)))+
geom_bar(stat='identity')
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
I want to plot a chart in R where it will show me vertical lines for each type in facet.
df is the dataframe with person X takes time in minutes to reach from A to B and so on.
I have tried below code but not able to get the result.
df<-data.frame(type =c("X","Y","Z"), "A_to_B"= c(20,56,57), "B_to_C"= c(10,35,50), "C_to_D"= c(53,20,58))
ggplot(df, aes(x = 1,y = df$type)) + geom_line() + facet_grid(type~.)
I have attached image from excel which is desired output but I need only vertical lines where there are joins instead of entire horizontal bar.
I would not use facets in your case, because there are only 3 variables.
So, to get a similar plot in R using ggplot2, you first need to reformat the dataframe using gather() from the tidyverse package. Then it's in long or tidy format.
To my knowledge, there is no geom that does what you want in standard ggplot2, so some fiddling is necessary.
However, it's possible to produce the plot using geom_segment() and cumsum():
library(tidyverse)
# First reformat and calculate cummulative sums by type.
# This works because factor names begins with A,B,C
# and are thus ordered correctly.
df <- df %>%
gather(-type, key = "route", value = "time") %>%
group_by(type) %>%
mutate(cummulative_time = cumsum(time))
segment_length <- 0.2
df %>%
mutate(route = fct_rev(route)) %>%
ggplot(aes(color = route)) +
geom_segment(aes(x = as.numeric(type) + segment_length, xend = as.numeric(type) - segment_length, y = cummulative_time, yend = cummulative_time)) +
scale_x_discrete(limits=c("1","2","3"), labels=c("Z", "Y","X"))+
coord_flip() +
ylim(0,max(df$cummulative_time)) +
labs(x = "type")
EDIT
This solutions works because it assigns values to X,Y,Z in scale_x_discrete. Be careful to assign the correct labels! Also compare this answer.
This question already has answers here:
How do I change the number of decimal places on axis labels in ggplot2?
(4 answers)
Closed 4 years ago.
I want to produce a bar plot, similar to this MWE:
library(tidyverse)
library(ggplot2)
mtcars %>%
mutate(mpg=mpg/1000) %>%
ggplot(aes(x=cyl, y=mpg)) +
geom_bar(stat="identity") +
scale_y_continuous(labels = scales::percent)
What I get is the following (keep in mind that it is nonsense, but serves illustration purposes):
Now, I want the decimals replaced from the percentages on the y-axis ("30%" instead of "30.0%"). What can I do?
I have found a similar question here, but couldn't make the function NRPercent does not work (and can't comment there).
With the new version of scales you can use:
scale_y_continuous(labels = scales::percent_format(accuracy = 1))
Here is a post that would help out : How do I change the number of decimal places on axis labels in ggplot2?
I posted the solution here just so you have it here. Added percent sign to values.
mtcars %>%
mutate(mpg=mpg/1000) %>%
ggplot(aes(x=cyl, y=mpg*100)) +
geom_bar(stat="identity") +
scale_y_continuous("Percent", labels = function(x) paste0(sprintf("%.0f", x),"%"))