Here's my initial barchart code:
Full %>% ggplot(aes(x = reorder(POS, -Iconicity), y = Iconicity, fill = Group)) +
geom_bar(stat = "summary", position=position_dodge(width = 0.9)) +
scale_fill_viridis_d() + # color-blind compatible colors
theme_minimal() + xlab("POS")
Which creates this lovely chart:
So I wanted to turn this into a lollipop chart to make it look neater and more modern, and this is the code I used:
Full %>% ggplot(aes(x = reorder(POS, -Iconicity), y = Iconicity, color = Group)) +
geom_point(size=3, stat = "summary", position=position_dodge(width = 0.9)) +
geom_segment(aes(x=POS,
xend=POS,
y=0,
yend=Iconicity)) +
scale_fill_viridis_d() + # color-blind compatible colors
theme_minimal() + xlab("POS")
However of course that does not add enough segments to the right places and I can't seem to work out how to change to code. What I'm left with is this:
I'm still quite a novice at R clearly so forgive me
I think the issue is coming from the fact you summarise your geom_point and not geom_segment and you are using position_dodge in geom_point.
Without a reproducible example of what is Full, it is hard to be sure of the answer to your question, but maybe you can try to summarise your values outside of ggplot and apply the same position_dodge to every geom:
Full %>%
group_by(Group) %>%
summarise(Iconicity = mean(Iconicity, na.rm = TRUE)) %>%
ggplot(aes(x = reorder(POS, -Iconicity), y = Iconicity, color = Group)) +
geom_point(size=3,position=position_dodge(width = 0.9)) +
geom_segment(aes(x=POS,
xend=POS,
y=0,
yend=Iconicity), position = position_dodge(0.9) ) +
scale_fill_viridis_d() + # color-blind compatible colors
theme_minimal() + xlab("POS")
Does it answer your question ?
If not, please provide a reproducible example of what is your Full Dataset (see this link: How to make a great R reproducible example)
Related
I'm trying to make a plot across two factors (strain and sex) and use the alpha value to communicate sex. Here is my code and the resulting plot:
ggplot(subset(df.zfish.data.overall.long, day=='day_01' & measure=='distance.from.bottom'), aes(x=Fish.name, y=value*100)) +
geom_boxplot(aes(alpha=Sex, fill=Fish.name), outlier.shape=NA) +
scale_alpha_discrete(range=c(0.3,0.9)) +
scale_fill_brewer(palette='Set1') +
coord_cartesian(ylim=c(0,10)) +
ylab('Distance From Bottom (cm)') +
xlab('Strain') +
scale_x_discrete(breaks = c('WT(AB)', 'WT(TL)', 'WT(TU)', 'WT(WIK)'), labels=c('AB', 'TL', 'TU', 'WIK')) +
guides(color=guide_legend('Fish.name'), fill=FALSE) +
theme_classic(base_size=10)
I'd like for the legend to reflect the alpha value in the plot (i.e. alpha value F = 0.3, alpha value M=0.9) as greyscale/black as I think that will be intuitive.
I've tried altering the scale_alpha_discrete, but cannot figure out how to send it a single color for the legend. I've also tried playing with 'guides()' without much luck. I suspect there's a simple solution, but I cannot see it.
One option to achieve your desired result would be to set the fill color for the alpha legend via the override.aes argument of guide_legend.
Making use of mtcars as example data:
library(ggplot2)
ggplot(mtcars, aes(x = cyl, y = mpg)) +
geom_boxplot(aes(fill = factor(cyl), alpha = factor(am))) +
scale_alpha_discrete(range = c(0.3, 0.9), guide = guide_legend(override.aes = list(fill = "black"))) +
scale_fill_brewer(palette='Set1') +
theme_classic(base_size=10) +
guides(fill = "none")
#> Warning: Using alpha for a discrete variable is not advised.
I was wondering if anyone has a solution for me as I would like to visualize a stacked bar chart that kinda looks like this:
This was made with a little data.table and the ggplot code below
library(data.table)
library(ggplot2)
dt <- data.table(id = seq(15), pvalue = c(0.0323616533686601, 0.00405825892193357, 0.00406609088355357, 0.00252697950679603, 0.00277696431629866, 0.0212521760053885, 0.0315721033650767, 0.00716594255390525, 0.00829537987151543, 0.0163753389504665, 0.0328650069220695, 0.0146991756928858, 0.0178425139730873, 0.00345987886149332, 0.0499748920124661))
ggplot(dt, aes(1, id, fill = pvalue)) + geom_bar(stat = 'identity')
But I'm looking for a slight modification. The data has an id column ranging from 1 to 15, this causes every item to have the corresponding size. But I would like to have them the same height/size.
This can be achieved with this bit of code:
ggplot(dt, aes(id, fill = pvalue)) + geom_bar(stat = 'count') + coord_flip()
But when I run this bit, I loose the ability to color them correctly (with scale_fill_gradient2)
Let me know if you find a nice solution :)
I think adding group= is what you are after:
ggplot(dt, aes(y=id, fill = pvalue, group=id)) +
geom_bar()
And if you define y= you don't need to coord_flip()
ps, geom_col() is the same as geom_bar(stat = 'identity')
I've made a histogram graph that shows the distribution of lidar returns per elevation for three lidar scans I have done.
I've converted my data to long format, with:
one column called 'value', describing the z position of each point
one column called 'variable', containing the name of each
scan group
In the attached image you can see the histograms of my three scan groups. I am currently using viridis to color the histogram by scan group (ie. the name of the scan in the variable column). However, I want to match the colours in the graph with colours I already have.
How might I do this?
The hexcols I'd like to like color each of my three histograms with are:
lightgreen = "#62FE96"
lightred = "#FE206B"
darkpurple = "#62278E"
A link to my data - 'density2'
My current code:
library(tidyverse)
library(viridisLite)
library(viridis)
# histogram
p <- density2 %>%
ggplot( aes(x=value,color = variable, show.legend = FALSE)) +
geom_histogram(binwidth = 1, alpha = 0.5, position="identity") +
scale_color_viridis(discrete =TRUE) +
scale_fill_viridis(discrete=TRUE) +
theme_bw() +
labs(fill="") +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
p + scale_y_sqrt() + theme(legend.position="none") + labs(y = "data pts", x = "elevation (m)")
Any help would be most appreciated!
Delete the scale_color_viridis and scale_fill_viridis lines - these are applying the Viridis color scale. Replace with scale_fill_manual(values = c(lightgreen, lightred, darkpurple)). And in your aesthetic mapping replace color = variable with fill = variable. For a histogram, color refers to the color of the lines outlining each bar, and fill refers to the color each bar is filled in.
This should leave you with:
p <- density2 %>%
ggplot(aes(x = value, fill = variable)) +
geom_histogram(binwidth = 1, alpha = 0.5, position = "identity") +
scale_fill_manual(values = c(lightgreen, lightred, darkpurple)) +
theme_bw() +
labs(fill = "") +
theme(panel.grid = element_blank())
p + scale_y_sqrt() +
theme(legend.position = "none") +
labs(y = "data pts", x = "elevation (m)")
I've also done some other clean-up. show.legend = FALSE does not belong inside aes() - and your theme(legend.position = "none") should take care of it.
I did not download your data, save it in my working directory, import it into R, and test this code on it. If you need more help, please post a small subset of your data in a copy/pasteable format (e.g., dput(density2[1:20, ]) for the first 20 rows---choose a suitable subset) and I'll be happy to test and adjust.
I've made a violin plot that looks like this:
As we can see most of the data lies near the region where the score is 0.90-0.95. What I wish is to focus on the interval 0.75 to 1.00 by changing the scale giving less space to ratings from 0 to 0.75.
Is there a way to do this?
This is the code I'm currently using to create the violin plot:
ggplot(data=Violin_plots, aes(x = Year, y = Score)) +
geom_violin(aes(fill = Violin_plots$Year), trim = TRUE) +
coord_flip()+
scale_fill_brewer(palette = "Blues") +
theme(legend.position = 'none') +
labs(y = "Rating score",
fill = "Rating year",
title = "Violin-plots of credit rating scores")
While it's possible to transform the scale to focus more in the upper region (e.g. add trans = "exp" as an argument to the scale), a non linear scale is often hard to interpret appropriately.
For such use cases, I recommend facet_zoom from the ggforce package, which is pretty much built for this exact purpose (see vignette here).
I also switched from geom_violin() + coord_flip() to geom_violinh from the ggstance package, which extends ggplot2 by providing flipped versions of ggplot components. Example with simulated data below:
library(ggforce) # for facet_zoom
library(ggstance) # for flipped version of geom_violin
ggplot(df,
aes(x = rating, y = year, fill = year)) +
geom_violinh() + # no need to specify trim = TRUE as it's the default
scale_fill_brewer(palette = "Blues") +
theme(legend.position = 'none') +
facet_zoom(xlim = c(0.75, 0.98)) # specify zoom range here
Sample data that simulates the characteristics of the data in the question:
df <- diamonds[, c("color", "price")]
df$rating <- (max(df$price) - df$price) / max(df$price)
df$year <- df$color
You could create a second plot to zoom in on the original plot, without modifying the data, by using ggplot2::coord_cartesian()
ggplot(data=Violin_plots, aes(x=Year,y=Score*100)) +
geom_violin(aes(fill=Violin_plots$Year),trim=TRUE) +
coord_flip() +
coord_cartesian(xlim = c(0.75, 1.00)) +
scale_fill_brewer(palette="Blues") +
theme(legend.position='none') +
labs(y="Rating score",fill="Rating year",title="Violin-plots of credit rating scores")
I am trying to combine fill and color in a ggplot2 legend. Because there are several colors for the x axis, it seems logic that ggplot2 do not know which color to pick in the legend.
For exemple:
library(ggplot2)
ggplot(mpg, aes(fl, hwy)) +
geom_point(aes(color = fl, shape = factor(year), fill = fl)) +
scale_shape_manual(values = c("circle filled", "circle open"))
My goal would be to manually edit the factor(year) legend to look like this:
I played around the guides() function without success.
Edit:
Values for shape can be found by running vignette("ggplot2-specs").
you already had the nearly correct answer with the scale_shape_manual. But somehow the "circle filled" argument is invalid. Since i'm not sure where those values can be looked up, i took the values from a table of a similar question (source):
so with value 20 and 79 you can get the desired result.
ggplot(mpg, aes(fl, hwy)) +
geom_point(aes(color = fl, shape = factor(year), fill = fl)) +
scale_shape_manual(values = c(16,79))
output:
Ok, so here is a very roundabout way of making it look like the image above. Maybe someone else can come up with a more intuitive version:
ggplot(mpg, aes(fl, hwy)) +
geom_point(aes(color = fl, shape = factor(year), fill = factor(year))) +
scale_shape_manual(values = c(16,79), guide = FALSE) +
scale_fill_manual("Year", values=c("grey","white"))+
guides(fill = guide_legend(override.aes = list(shape = c(21,21),
color = c("black", "black"))))
Output: