Why I cannot add colours to my bar chart in Rstudio? [duplicate] - r

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')

Related

Order bar chart by another variable in ggplot [duplicate]

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

R, ggplot: Decimals on y-axis [duplicate]

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),"%"))

How to add legends in ggplot2? [duplicate]

This question already has answers here:
Add legend to ggplot2 line plot
(4 answers)
Closed 4 years ago.
Probably very basic question about the legends in ggplot2 (sorry i am basic user user of R), I use this:
p<-ggplot(bAfr_topS1, aes(MAF, V3))+ geom_point()
p <- p+ geom_point(data=bEur_topS1,aes(MAF,V3),colour="red")+
geom_point(data = bSas_topS1, aes(MAF, V3), colour="blue")
print(p)
but can't see the legends in output plot, any suggestion please? what should i add in?
It's difficult to give specific help without any data, but to illustrate the point #PoGibas is making and to get you started, try the following
library(tidyverse)
bind_rows(list(AF = bAfr_topS1, EU = bEur_topS1, PK = bSas_topS1), .id = "src") %>%
ggplot(aes(MAF, V3, colour = as.factor(src))) +
geom_point()
This assumes that bAfr_topS1, bEur_topS1, bSas_topS1 all have the same column structure.

Summary plot of ggplot2 facets as a facet [duplicate]

This question already has answers here:
Easily add an '(all)' facet to facet_wrap in ggplot2?
(3 answers)
Closed 5 years ago.
It is often the case that we produce facets to decompose the data according to a variable, but that we still would like to see a summary as a stack of the facets. Here is an example:
library(ggplot2)
ggplot(data=iris, aes(x=Sepal.Length,y=Petal.Length)) +
geom_point(aes(color=Species)) +
facet_wrap(~Species, ncol=2)
However, I would also like that one of the facets is the overlay of the 3 facets:
ggplot(data=iris, aes(x=Sepal.Length,y=Petal.Length)) +
geom_point(aes(color=Species))
Is there anyway of doing this easily?
Many thanks,
I wrote the following function to duplicate the dataset and create an extra copy under of the data under variable all.
library(ggplot2)
# Create an additional set of data
CreateAllFacet <- function(df, col){
df$facet <- df[[col]]
temp <- df
temp$facet <- "all"
return(rbind(temp, df))
}
Instead of overwriting the original facet data column, the function creates a new column called facet. The benefit of this is that we can use the original column to specify the aesthetics of the plot point.
df <- CreateAllFacet(iris, "Species")
ggplot(data=df, aes(x=Sepal.Length,y=Petal.Length)) +
geom_point(aes(color=Species)) +
facet_wrap(~facet, ncol=2)
I feel the legend is optional in this case, as it largely duplicates information already available within the plot. It can easily be hidden with the extra line + theme(legend.position = "none")

Add customized labels over bars in ggplot [duplicate]

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:

Resources