Remove decimals y axis ggplot2 - r

I have data that looks like this, df_Filtered:
Product Relative_Value
Car 0.12651458
Plane 0.08888552
Tank 0.03546231
Bike 0.06711630
Train 0.06382191
I want to make a bar plot of the data in GGplot2:
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = scales::percent) +
geom_bar(stat = "identity") +
theme_bw() +
theme(plot.background = element_rect(colour = "black", size = 1)) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5))
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
theme(panel.grid.major = element_blank())
How do i get rid of the decimals on the y-axis in the chart? So that it says 20 % instead of 20.0 %?

Use percent_format from the scales package to set accuracy to 1.
library(ggplot2)
library(scales)
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
geom_bar(stat = "identity") +
theme_bw() +
theme(plot.background = element_rect(colour = "black", size = 1)) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5)) +
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
theme(panel.grid.major = element_blank())
DATA
df_Filtered <- read.table(text = "Product Relative_Value
Car 0.12651458
Plane 0.08888552
Tank 0.03546231
Bike 0.06711630
Train 0.06382191",
header = TRUE, stringsAsFactors = FALSE)

scales::percent_format(accuracy = 2) doesn't allow manual breaks = c(0, 0.5, .10).
So, I have to create the manual function scale_y_continuous(breaks = c(0, 0.5, .10), labels = function(x) paste0(round(as.numeric(x*100)), "%")) .

Related

Color for facet grid, based on x-axis, in ggplot2

I have color for each variable (fishing strategy), however, if I put it in a facet grid like this, based on the years, I can't set up the colors accordingly. I want to have one color for each fishing strategy instead of one color for each year, but also need the legend for fishing strategies with color or just years without color. But I didn't manage to do that. Can someone help me with this?
With this code:
spaclu <- ggplot(io1, aes(y= effort, x=factor(clu_name2), fill= factor(year))) + geom_bar(stat="identity", position="dodge")
+ theme_minimal()
spaclu + facet_grid(vessel_category~geartype_clu2, scales = "free")
+ labs(fill = "Year", x = "Fishing strategies", y = "Total REA", title = "Based on the REA")
+ theme(text = element_text(size = 13))
+ theme(legend.position = "bottom")
+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
+
scale_fill_manual(values = c("GIL_COD" = "#004c6d",
"GIL_FRS" = "#00ffff",
"GIL_FLE" = "#00a1c1",
"GIL_HER" = "#00cfe3",
"PAS_FLA" = "#78ab63",
"POL_FRS" = "#6efa75",
"BST_MIX" = "#ffc334",
"MPT_HER" = "#ff9509",
"BPT_HER" = "#ffb6de",
"BPT_COD" = "#cc0089"))
I get this
but if I removed the scale fill manual part, it looked like this
I think I've worked it out, but I don't have your data. (It's a bit messy.)
I used the dataset diamonds and renamed the fields. The first plot is supposed to represent your second plot, where you have removed the scale_color_manual.
The data first:
library(tidyverse)
# create variables
io1 <- diamonds %>%
mutate(year = cut,
effort = x,
clu_name2 = color,
vessel_category = rep(c("Passive","Active"), nrow(diamonds)/2),
geartype_clu2 = rep(LETTERS[1:3], nrow(diamonds)/3))
levels(io1$year) <- c(2019:2023)
Original plot as you've coded:
# grid faceting/color
spaclu <- ggplot(io1, aes(y= effort, x=factor(clu_name2), fill= factor(year))) +
geom_col(position = "dodge") +
theme_minimal()
spaclu + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "Year", x = "Fishing strategies", y = "Total REA",
title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
The primary differences are the arguments group = year and fill = clu_name2.
p2 <- ggplot(io1, aes(x = clu_name2, y = effort, group = year, fill = clu_name2)) +
geom_col(position = "dodge") +
theme_minimal()
p2 + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "", x = "Fishing strategies\ngrouped by years",
y = "Total REA", title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
Keep in mind the legend here is fishing strategies. If you want the years shown, perhaps a second depth label with scale_fill_manual() would be a good approach.
Now as far getting the years and the strategies in the legend or as legends. You may be better off with adding a second scale axis and using the first version. This can be done with the package ggnewscale. You'll have to adjust the font size or expand or add to the margin, though.
# grid faceting/color
spaclu <- ggplot(io1, aes(y= effort, x=factor(clu_name2), fill= factor(year),
group = year)) +
geom_col(position = "dodge") +
theme_minimal()
spaclu + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "Year", x = "Fishing strategies", y = "Total REA",
title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggnewscale::new_scale("fill") + # added scale here
geom_tile(aes(fill = clu_name2, y = 1)) +
scale_fill_discrete(name = "Strategies")
It doesn't quite work out when using it with the second option
p2 <- ggplot(io1, aes(x = clu_name2, y = effort, group = year, fill = clu_name2)) +
geom_col(position = "dodge") +
theme_minimal()
p2 + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "", x = "Fishing strategies\ngrouped by years",
y = "Total REA", title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_manual(values = c("D" = "#004c6d",
"E" = "#00ffff",
"F" = "#00a1c1",
"G" = "#00cfe3",
"H" = "#78ab63",
"I" = "#6efa75",
"J" = "#ffc334",
"K" = "#ff9509",
"L" = "#ffb6de",
"M" = "#cc0089")) +
ggnewscale::new_scale("fill") +
geom_tile(aes(fill = year, y = 1)) +
scale_fill_viridis_d(name = "Years")

Setting all theme elements blank does not affect the axis elemenets

I have the dataframe below
GO<-c("cytosol (GO:0005829)","cytosol (GO:0005829)")
FE<-c(2.70,4.38)
FDR<-c(0.00159,0.00857)
Facet<-c("ileum 24h","ileum 72h")
CCC<-data.frame(GO,FE,FDR,Facet)
and with this code
CCC %>%
arrange(desc(CCC$GO))%>%
ggplot(aes(x = FDR, y = GO, size = FE, color = FDR)) +
geom_point(alpha = 0.5) +
scale_size(range = c(5, 8), name = "Fold enrichment") +
facet_grid(cols = vars(Facet), scales = "free") +
theme(axis.title.x=element_blank(),axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1)) +
scale_y_discrete(name = "GO biological process complete") +
scale_x_continuous(name = "FDR") +
scale_colour_gradient(low = "yellow", high = "red", name = "FDR") +
theme_bw()
I create a bubble plot with facets. But I want to delete the x-axis title 'FDR' and display the labels with an angle but despite setting the theme() it does not change.
You have put theme_bw() at the end, which over-writes your theme call. Put your custom themes at the end:
CCC %>%
arrange(desc(CCC$GO))%>%
ggplot(aes(x = FDR, y = GO, size = FE, color = FDR)) +
geom_point(alpha = 0.5) +
scale_size(range = c(5, 8), name = "Fold enrichment") +
scale_y_discrete(name = "GO biological process complete") +
scale_x_continuous(name = "FDR") +
scale_colour_gradient(low = "yellow", high = "red", name = "FDR") +
facet_grid(cols = vars(Facet), scales = "free") +
theme_bw() +
theme(axis.title.x = element_blank(),
axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1))
I think it is good practice to lay out your calls to ggplot in a consistent way so that this kind of thing doesn't happen:
Call ggplot +
Geom (and stat) layers, ordered depending on which ones you want on top +
Scales +
Facets +
Labels and titles +
Global themes like theme_bw() +
Individual theme tweaks via theme
Only change the position of theme_bw():
library(tidyverse)
#Data
GO<-c("cytosol (GO:0005829)","cytosol (GO:0005829)")
FE<-c(2.70,4.38)
FDR<-c(0.00159,0.00857)
Facet<-c("ileum 24h","ileum 72h")
CCC<-data.frame(GO,FE,FDR,Facet)
#Plot
CCC %>%
arrange(desc(CCC$GO))%>%
ggplot(aes(x = FDR, y = GO, size = FE, color = FDR)) +
geom_point(alpha = 0.5) +
scale_size(range = c(5, 8), name = "Fold enrichment") +
facet_grid(cols = vars(Facet), scales = "free") +
xlab('')+
theme_bw()+
theme(axis.title.x=element_blank(),
axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1)) +
scale_y_discrete(name = "GO biological process complete") +
scale_x_continuous(name = "") +
scale_colour_gradient(low = "yellow", high = "red", name = "FDR")
Output:

How to change the way a single value is represented from a bar to a line?

I am working with a dataset that I found on wikipedia regarding the nutritional content of staple grains. I scraped the data table using the rvest package and created the graphic shown below
It was pointed out to me that perhaps it might be better to represent the "Recommended Dietary Allowance"(RDA) with a vertical line as opposed to a bar.
1) How to a create the separate vertical line representing "Recommended Dietary Allowance"?
The code used to create the graphic is below: I am not sure on whether I should include the code used to gather and wrangle the data. Please let me know if that would help.
ggplot(grain.nut, aes(grain, nutrients, fill = grain)) +
facet_wrap(~ nutrient.component., scales = "free") +
geom_bar(stat = "identity", position = "dodge") +
coord_flip() +
labs(title = "Nutrient Content of Major Staple Foods per 100 gram Portion",
caption = "https://en.wikipedia.org/wiki/Staple_food#Nutritional_content") +
theme(plot.title = element_text(size = 30, face = "bold")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.y = element_blank()) +
theme(panel.grid.major.y = element_blank()) +
theme(panel.grid.minor.y = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.position = c(0.80,0.05), legend.direction = "horizontal") +
theme(legend.title = element_blank()) +
theme(plot.caption = element_text(hjust = 0.84)) +
guides(fill=guide_legend(reverse=TRUE)) +
scale_fill_manual(values = c("#e70000",
"#204bcc",
"#68ca3b",
"#fe9bff",
"#518901",
"#de0890",
"#fcba4c",
"#292c7a",
"#e69067",
"#79b5ff",
"#68272d",
"#c9cb6c"))
I have tried using geom_vline as well as geom_hline. But I think my problem is the way I am trying to call the value for RDA via levels(grain.nut$grain)1, the output of which is "Recommended Dietary Allowance".
geom_vline(aes(xintercept = levels(grain.nut$grain)[1]))
Any help would be appreciated!
Here is an approach using geom_linerange or geom_pointrange.
First the data:
library("rvest")
library(tidyverse)
url <- "https://en.wikipedia.org/wiki/Staple_food"
nutrient <- url %>%
read_html() %>%
html_nodes(xpath='//*[#id="mw-content-text"]/div/table[2]') %>%
html_table()
get the correct order of levels for discrete scale:
lev = levels(as.factor(z$grain))[c(1:4,6:12, 5)]
The plot:
ggplot() +
geom_col(data = nutrient[[1]] %>%
as.tibble() %>%
gather(grain, value, 2:ncol(.)) %>%
filter(grain!="RDA") %>%
mutate(nutrient = `Nutrient component:`,
value = as.numeric(value)), aes(grain, value, fill = grain), position = "dodge")+
geom_pointrange(data = nutrient[[1]] %>%
as.tibble() %>%
gather(grain, value, 2:ncol(.)) %>%
filter(grain=="RDA") %>%
mutate(nutrient = `Nutrient component:`,
value = as.numeric(value)), aes(x = grain, ymin = 0, ymax = value, y = value, color = grain), size = 0.3, show.legend = F)+
facet_wrap(~ nutrient, scales = "free") +
scale_x_discrete(limits = lev) +
coord_flip() +
labs(title = "Nutrient Content of Major Staple Foods per 100 gram Portion",
caption = "https://en.wikipedia.org/wiki/Staple_food#Nutritional_content") +
theme(plot.title = element_text(size = 30, face = "bold")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.y = element_blank()) +
theme(panel.grid.major.y = element_blank()) +
theme(panel.grid.minor.y = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.position = c(0.80,0.05), legend.direction = "horizontal") +
theme(legend.title = element_blank()) +
theme(plot.caption = element_text(hjust = 0.84)) +
guides(fill=guide_legend(reverse=TRUE)) +
scale_fill_manual(values = c("#e70000",
"#204bcc",
"#68ca3b",
"#fe9bff",
"#518901",
"#de0890",
"#fcba4c",
"#292c7a",
"#e69067",
"#79b5ff",
"#68272d",
"#c9cb6c"))
Basically two layers are used with different data: geom_col with data without RDA and geom_pointrange for data with only RDA. And the order is changed in scale_x_discrete to match the lev object.
If you do not like the points use geom_linerange and omit the y in he aes call
or did u mean this?
ggplot() +
geom_col(data = nutrient[[1]] %>%
as.tibble() %>%
gather(grain, value, 2:ncol(.)) %>%
filter(grain!="RDA") %>%
mutate(nutrient = `Nutrient component:`,
value = as.numeric(value)), aes(grain, value, fill = grain), position = "dodge")+
geom_hline(data = nutrient[[1]] %>%
as.tibble() %>%
gather(grain, value, 2:ncol(.)) %>%
filter(grain=="RDA") %>%
mutate(nutrient = `Nutrient component:`,
value = as.numeric(value)), aes(yintercept = value), show.legend = F)+
facet_wrap(~ nutrient, scales = "free") +
coord_flip() +
labs(title = "Nutrient Content of Major Staple Foods per 100 gram Portion",
caption = "https://en.wikipedia.org/wiki/Staple_food#Nutritional_content") +
theme(plot.title = element_text(size = 30, face = "bold")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.y = element_blank()) +
theme(panel.grid.major.y = element_blank()) +
theme(panel.grid.minor.y = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.position = c(0.80,0.05), legend.direction = "horizontal") +
theme(legend.title = element_blank()) +
theme(plot.caption = element_text(hjust = 0.84)) +
guides(fill=guide_legend(reverse=TRUE)) +
scale_fill_manual(values = c("#e70000",
"#204bcc",
"#68ca3b",
"#fe9bff",
"#518901",
"#de0890",
"#fcba4c",
"#292c7a",
"#e69067",
"#79b5ff",
"#68272d",
"#c9cb6c"))

ggplot pie chart choose axes ticks

I would like to know if it's possible to modify the ticks of x axis with a ggplot pie chart.
Here what I can do :
# Some colors
couleurs <- data.frame(
id=seq(1,17,1),
mix=c(c(rep(1,6),rep(2,7),rep(3,4))),
html=c("#A00020","#109618","#388EE4","#C484D1","#FFAA33","#CCCDD0","#004AC5","#F80094","#CB5023","#638995","#33CFCF","#95DC4E","#F7D633","#5C403C","#F72020","#00D96C","#FDE4C5")
)
couleurs$html <- factor(couleurs$html, levels = couleurs$html[order(couleurs$id, decreasing = FALSE)])
# Data
activite <- data.frame(label=c("B to B","B to C","B to B / B to C", "B to B"), cible=c(rep("Externe",3), "Interne"), nb=c(12,9,3,12))
activite$label <- factor(activite$label, levels = activite$label[order(activite$nb[activite$cible=="Externe"], decreasing = TRUE)])
library(plyr)
activite<-ddply(activite,.(cible),transform,pc=(nb/sum(nb))*100)
activite
# Pie chart
library(ggplot2)
ggplot(data = activite, aes(x = "", y = nb, fill = label )) +
geom_bar(stat = "identity", position = position_fill(), width = 1) +
coord_polar(theta= "y", start = 0, direction = -1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white", fontface = "bold", position = position_fill(vjust = 0.5)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_line(colour = "grey75")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.length = unit(0, "mm")) +
theme(axis.title.x = element_blank(),axis.title.y = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Here my result:
After several hours of serach, I didn't find a solution to create what I want. The exact same pie chart but with personalised ticks like that :
With these particular conditions :
- do not change the direction of the data in the pie chart, I want it like exactly this
- if possible (but if not possible, it's okay), I would like the ticks' labels not superposed with the axis.
If someone can help me, I would really appreciate.
Here's one solution:
ggplot(data = activite %>%
group_by(cible) %>%
arrange(desc(nb)) %>%
mutate(axis.label = cumsum(nb),
axis.position = cumsum(pc)/100) %>%
mutate(axis.label = ifelse(pc == min(pc),
paste(axis.label, "0", sep = "-"),
axis.label)),
aes(x = 1, y = nb, fill = label )) +
geom_segment(aes(x = 1, xend = 1.6, y = axis.position, yend = axis.position),
colour = "grey75") +
geom_vline(xintercept = 1.6, colour = "grey75") +
geom_bar(stat = "identity", position = position_fill(reverse = T), width = 1) +
coord_polar(theta= "y", start = 0, direction = 1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white",
fontface = "bold", position = position_fill(vjust = 0.5, reverse = T)) +
geom_text(aes(x = 1.7, label = axis.label), size = 3,
position = position_fill(reverse = T)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.text = element_blank()) +
theme(axis.ticks = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Explanation:
The sequence in your labels went clockwise, while the direction of the polar coordinates went counter-clockwise. That makes labelling rather troublesome. I switched the direction for polar coordinates, & added reverse = T inside the position adjustment calls for the geoms.
It's hard to assign different axis breaks to different facets of the same plot, so I didn't. Instead, I modified the data to include calculated axis labels / margin positions, added margins via geom_segment / geom_vline, & hid the axis text / ticks in theme().

How to order a heatmap in R by x or y?

I've created a heatmap on temperatures by city. ggplot orders cities by default, from Z-A, not what I want. How can I change the code so that the cities would be ordered A-Z, how overall x and y can be ordered in ggplot ?
ggplot(Cities, aes(x = Month, y = City, fill = AvgTemp, frame = City)) +
geom_tile(color = "white", size = 0.5) +
scale_fill_gradient(name = "Average Temperature",low = "blue", high = "red") +
coord_equal() +
labs(x = "Month", y = "", title = "Average Temp") +
theme_tufte() +
theme(axis.ticks = element_blank()) +
theme(axis.text = element_text(size = 15)) +
theme(plot.title = element_text(size = 15)) +
theme(legend.title = element_text(size = 10)) +
theme(legend.text = element_text(size = 10))
I've included a reorder in your aes(y=).
ggplot(data=Cities) +
geom_tile( aes(x=Month, y=reorder(City, AvgTemp, median, order=TRUE), fill = AvgTemp), color = "white", size = 0.5) +
scale_fill_gradient(name = "Average Temperature",low = "blue", high = "red") +
coord_equal() +
labs(x = "Month", y = "", title = "Average Temp") +
theme_tufte()

Resources