How to combine line and points to a same legend? - ggplot2

Here is my data frame
Days,Observed,Simulated
0,0,653.8209779
1,982,1300.359539
2,2002,2245.28519
3,3086,3465.029007
4,4290,4891.001133
5,6030,6431.473538
6,7658,7994.170186
7,9063,9501.969562
8,10405,10899.95599
9,11625,12155.67626
10,12759,13255.52404
11,13949,14199.72821
12,14961,14997.49918
13,16151,15663.0628
14,16931,16212.76706
15,17554,16663.16302
16,17874,17029.85323
17,18114,17326.89033
18,18231,17566.54139
19,18231,17759.27762
20,18231,17913.89111
The cod I used is as follows:
R <- ggplot(Data, aes(x = Days)) +
geom_line(aes(y = Simulated, color="Simulated")) +
geom_point(aes(y = Observed, color="Observed"))
a <- ggtitle("C14=2kg of Placenta & 0.8kg of seed")
n <- scale_color_calc(name = "Legend")
c <- labs(x = 'Time(Days)', y = "Cumulative Biogas Yield(ml)")
h <- theme(plot.title = element_text(hjust = 0.1))
o <- theme(
plot.title = element_text(colour = "black"),
axis.title.x = element_text(colour = "black", size = 10),
axis.title.y = element_text(colour = "black", size = 10),
legend.title = element_text(colour = "black", size = 12.5),
legend.text = element_text(colour = "black", size = 10),
axis.text.x = element_text(colour = "black", size = 10),
axis.text.y = element_text(colour = "black", size = 10))
MyPlot <- R+a+n+c+h+o
MyPlot
This is what I got.
The legend shows combination of line and points
The legend shows combination of line and points
This is what I want.
Only Points in the legend of point
Only Points in the legend of point

Is this what you are looking for?
The issue relates to using the same aesthetic - colour - for different geoms.
You are not actually plotting red points so I am not sure why you want red dots in the legend?
library(ggplot2)
ggplot(df, aes(x = Days)) +
geom_line(aes(y = Simulated, color="Simulated")) +
geom_point(aes(y = Observed, fill = "Observed")) +
ggtitle("C14=2kg of Placenta & 0.8kg of seed")+
labs(x = 'Time(Days)',
y = "Cumulative Biogas Yield(ml)",
colour = NULL,
fill = "Legend title")+
theme(plot.title = element_text(hjust = 0.1))+
theme( plot.title = element_text(colour = "black"),
axis.title.x = element_text(colour = "black", size = 10),
axis.title.y = element_text(colour = "black", size = 10),
legend.title = element_text(colour = "black", size = 12.5),
legend.text = element_text(colour = "black", size = 10),
axis.text.x = element_text(colour = "black", size = 10),
axis.text.y = element_text(colour = "black", size = 10))
data
structure(list(Days = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20), Observed = c(0, 982, 2002,
3086, 4290, 6030, 7658, 9063, 10405, 11625, 12759, 13949, 14961,
16151, 16931, 17554, 17874, 18114, 18231, 18231, 18231), Simulated = c(653.8209779,
1300.359539, 2245.28519, 3465.029007, 4891.001133, 6431.473538,
7994.170186, 9501.969562, 10899.95599, 12155.67626, 13255.52404,
14199.72821, 14997.49918, 15663.0628, 16212.76706, 16663.16302,
17029.85323, 17326.89033, 17566.54139, 17759.27762, 17913.89111
)), class = "data.frame", row.names = c(NA, -21L))
Created on 2020-05-22 by the reprex package (v0.3.0)

Related

Colors don't stick when lollipop plot is run

I have created a lollipop chart that I love. However, when the code runs to create the plot, the colors of the lines, segments, and points all change from what they were set to. Everything else runs great, so this isn't the end of the world, but I am trying to stick with a color palette throughout a report.
The colors should be this ("#9a0138", and "#000775" specifically):
But come out like this:
Any ideas?
Here is the data:
TabPercentCompliant <- structure(list(Provider_ShortName = c("ProviderA", "ProviderA", "ProviderA", "ProviderB",
"ProviderB", "ProviderB", "ProviderC", "ProviderC", "ProviderC", "ProviderD"), SubMeasureID = c("AMM2", "FUH7", "HDO", "AMM2", "FUH7", "HDO", "AMM2", "FUH7", "HDO", "AMM2"), AdaptedCompliant = c(139, 2, 117, 85, 1, 33, 36, 2, 22, 43), TotalEligible = c(238, 27, 155, 148, 10, 34, 61, 3, 24, 76), PercentCompliant = c(0.584033613445378, 0.0740740740740741, 0.754838709677419, 0.574324324324324, 0.1, 0.970588235294118, 0.590163934426229, 0.666666666666667, 0.916666666666667, 0.565789473684211 ), PercentTotalEligible = c(0.00516358587173479, 0.00058578495183546, 0.00336283953831467, 0.00321096936561659, 0.000216957389568689, 0.000737655124533542, 0.001323440076369, 6.50872168706066e-05, 0.000520697734964853, 0.00164887616072203), ClaimsAdjudicatedThrough = structure(c(19024, 19024, 19024, 19024, 19024, 19024, 19024, 19024, 19024, 19024 ), class = "Date"), AdaptedNCQAMean = c(0.57, 0.39, 0.93, 0.57, 0.39, 0.93, 0.57, 0.39, 0.93, 0.57), PerformanceLevel = c(0.0140336134453782, -0.315925925925926, -0.175161290322581, 0.00432432432432439, -0.29, 0.0405882352941176, 0.0201639344262295, 0.276666666666667, -0.0133333333333334, -0.00421052631578944)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))
VBP_Report_Date = "2022-09-01"
And the code for the plot:
Tab_PercentCompliant %>%
filter(ClaimsAdjudicatedThrough == VBP_Report_Date) %>%
ggplot(aes(x = Provider_ShortName,
y = PercentCompliant)
) +
geom_line(aes(x = Provider_ShortName,
y = AdaptedNCQAMean,
group = SubMeasureID,
color = "#9a0138",
size = .001)
) +
geom_point(aes(color = "#000775",
size = (PercentTotalEligible)
)
) +
geom_segment(aes(x = Provider_ShortName,
xend = Provider_ShortName,
y = 0,
yend = PercentCompliant,
color = "#000775")
)+
facet_grid(cols = vars(SubMeasureID),
scales = "fixed",
space = "fixed")+
theme_classic()+
theme(legend.position = "none") +
theme(panel.spacing = unit(.5, "lines"),
panel.border = element_rect(
color = "black",
fill = NA,
linewidth = .5),
panel.grid.major.y = element_line(
color = "gray",
linewidth = .5),
axis.text.x = element_text(
angle = 65,
hjust=1),
axis.title.x = element_blank(),
axis.line = element_blank(),
strip.background = element_rect(
color = NULL,
fill = "#e1e7fa"))+
scale_y_continuous(labels = scales::percent)+
labs(title = "Test",
subtitle = "Test",
caption = "Test")
If you have an aesthetic constant, it is often easier / better to have it "outside" your aes call. If you want to have a legend for your color, then you need to keep it "inside", but you will need to manually set the colors with + scale_color/fill_manual.
I've had to cut down quite a lot in your code to make it work. I've also removed bits that are extraneous to the problem. I've removed line size = 0.001 or the line wasn't visible. I've removed the weird filter step or the plot wasn't possible.
Tips: when defining a global aesthetic with ggplot(aes(x = ... etc), you don't need to specify this aesthetic in each geom layer (those aesthetics will be inherited)- makes a more concise / readable code.
library(ggplot2)
ggplot(TabPercentCompliant, aes(x = Provider_ShortName, y = PercentCompliant)) +
geom_line(aes(y = AdaptedNCQAMean, group = SubMeasureID),
color = "#9a0138") +
geom_point(aes(size = PercentTotalEligible), color = "#000775") +
geom_segment(aes(xend = Provider_ShortName, y = 0, yend = PercentCompliant),
color = "#000775") +
facet_grid(~SubMeasureID) +
theme(strip.background = element_rect(color = NULL, fill = "#e1e7fa"))
Here is the final code. Thanks again tjebo!
# Lollipop Chart ----------------------------------------------------------
Tab_PercentCompliant %>%
filter(ClaimsAdjudicatedThrough == VBP_Report_Date) %>%
ggplot(aes(x = Provider_ShortName,
y = PercentCompliant)
) +
geom_line(aes(y = AdaptedNCQAMean,
group = SubMeasureID),
color = "#9a0138"
) +
geom_point(aes(size = PercentTotalEligible),
color = "#000775",
) +
geom_segment(aes(xend = Provider_ShortName,
y = 0,
yend = PercentCompliant),
color = "#000775"
)+
facet_grid(cols = vars(SubMeasureID)
)+
theme_bw()+
theme(legend.position = "none",
axis.text.x = element_text(
angle = 65,
hjust=1),
axis.title.x = element_blank(),
axis.line = element_blank(),
strip.background = element_rect(
fill = "#e1e7fa"))+
scale_y_continuous(labels = scales::percent)+
labs(title = "Test",
subtitle = "Test",
caption = "Test")

How do I separate the geom_label_repel in the geom_bar?

I want to pull away these overlapping labels in ggplot.
I am seeking for help to pull away each label to avoid overlapping. I've tried modify box.padding, max.overlaps, min.segment.length but still faild.
data = read.csv("995_matched_cancer_types.csv", header=T)
names(data) <- c("cancer_types","primary_disease","cell_lines")
data <- subset(data, data$primary_disease!="Unknown")
data["counts"] <- data$cell_lines/sum(data$cell_lines)
data["info"] <- paste0(data$cancer_types,"(",data$cell_lines,")")
ggplot(data, aes(x=1, y=counts, label=info, fill=cancer_types)) +
geom_bar(stat="identity", position = position_dodge2(), color="black") +
geom_text_repel(position=position_dodge2(.9),
box.padding = .5,
max.overlaps = 30,
min.segment.length = 0,
ylim = c(.03,Inf)) +
labs(x = NULL, y = NULL, fill = NULL)+
theme_classic() + theme(axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
strip.text = element_text(size = 12),
legend.position = "none"
)+
facet_wrap(~primary_disease)
If someone would help me with this problem, I would really appreciate it.
I have changed ylim = c(.03,Inf) to ylim = c(NA,Inf). This removes most of the overlaps. You can play around with the xlim and ylim values (in my opinion). You can try different height and width parameters of the ggsave function as well.
ggplot(data, aes(x=1, y=counts, label=info, fill=cancer_types)) +
geom_bar(stat="identity", position = position_dodge2(), color="black") +
geom_text_repel(position=position_dodge2(.9),
box.padding = 0.5,
max.overlaps = 30,
min.segment.length = 0,
ylim = c(NA,Inf)) +
labs(x = NULL, y = NULL, fill = NULL)+
theme_classic() + theme(axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
strip.text = element_text(size = 12),
legend.position = "none"
)+
facet_wrap(~primary_disease)
# save plot as png
ggsave("fig.png",
width = 20,
height = 10,
units = "in"
)

How to change a map tilt

I'm struggling with the map tilt. I would like help to change the tilt of the following map. Thanks!
The first map is my result, the second map is how I would like the slope to be.
library(usmap)
library (ggplot2)
read.table("NY_data.txt", header = T)->NY_data
NY1 <- plot_usmap(regions = "county", include = c("NY"), data = NY_data, values = "YEAR_2010") +
labs(title = "New York by county", subtitle = "2010") +
theme(plot.title = element_text(face="bold", size=18, hjust = 0.5),
plot.subtitle = element_text(face="bold", size=16)) +
scale_fill_continuous(low = "white", high = "#CB454A", limits=c(0, 35),
name = "Cumulative cases",
guide = guide_colourbar(barwidth = 27, barheight = 0.5,
title.position = "top"),
label = scales::comma) +
theme(legend.position = "bottom",
legend.title=element_text(size=12, face = "bold"),
legend.text=element_text(size=10))
NY1
map1
map2

Multi-row x-axis labels with breaks in R

I would like to add 2-row x-axis labels on my line plot, but not sure how to also incorporate the continuous labels and breaks I have for my 1st x-axis (Column "CYR" - short for calendar year). I'd like to have the 2nd axis (WYR) start half-way between the first label and the second (WYR = 2010 starts between CYR = 2009 -> 2010). I also wasn't sure how to add 2 x-axis titles either, maybe at the beginning of each x-axis row?
My data:
> dput(wet_pivot)
structure(list(WYR = c("WR_2010", "WR_2011", "WR_2012", "WR_2013",
"WR_2014", "WR_2015", "WR_2016", "WR_2017", "WR_2018", "WR_2019",
"WR_2020", "WR_2021", "WR_2022"), CYR = c(2009, 2010, 2011, 2012,
2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021), Season = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("DRY",
"WET"), class = "factor"), N = c(59L, 63L, 69L, 70L, 72L, 71L,
71L, 72L, 71L, 68L, 70L, 48L, 72L), n_mean = c(0.00696806934430411,
0.000649730847004026, 0.00288256551918419, 0.01141088388474,
0.000536174103147671, 0.00349584646220785, 0.000482925207291882,
0.00245359625194744, 0.00292096956686587, 0.00252817293686805,
0.00196286772014134, 0.00501799463867351, 0.00132244297252478
), n_median = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), sd = c(0.030946706350869,
0.00248965525641742, 0.0100973832581282, 0.051577934580242, 0.00331468784320076,
0.0266064084754242, 0.00212505905295283, 0.00675243933898364,
0.0119729983336735, 0.00639785127193391, 0.00930625647382774,
0.0136275258272549, 0.00543420856675111), se = c(0.00402891799826298,
0.000313667078988821, 0.00121558209746373, 0.0061647423020683,
0.000390639708573979, 0.00315759975690469, 0.000252198110662322,
0.000795782607691024, 0.00142093348159893, 0.000775853428563995,
0.00111231039833223, 0.00196696392618855, 0.000640427621321956
)), row.names = c(NA, -13L), class = "data.frame")
My attempt:
years <- seq(2009,2021,1)
labs <- seq(2009,2021,by=1)
myplot <- ggplot(wet_pivot, aes(x = CYR, y = n_mean)) +
geom_errorbar(aes(ymin=n_mean-se, ymax=n_mean+se), width=.2, color = "black") +
geom_point(color = "black", shape = 1, size = 2) +
geom_line(color = "black") +
scale_y_continuous(limits = c(0, 0.04), expand = expansion(mult = c(0, 0.05))) +
scale_x_continuous(breaks= years, labels = labs)
myplot +
annotate(geom = "text",
x = 1:nrow(wet_pivot),
y = min(wet_pivot$n_mean),
label = labs,
vjust = 3.5) +
annotate(geom = "text",
x = 1:nrow(wet_pivot),
y = min(wet_pivot$n_mean),
label = wet_pivot$WYR,
vjust = 5)
You indeed can use text annotations to substitute for x-axis labels. A few recommendations:
Set y = -Inf to automatically place text as bottom, independent of whatever data is on the plot. vjust can indeed be used to place it further down.
You'd need coord_cartesian(clip = "off") to actually show the text.
You can place 'titles' with an extra annotation layer, with x = -Inf to place it on the left.
I used the above for the example below. Maybe the text is still to big, so you could set the 8.8 / .pt to something smaller. (The / .pt translates between mm, which geom_text() uses, to points, which is used in theme)
library(ggplot2)
# wet_pivot <- structure(...) # omitted for previty
ggplot(wet_pivot, aes(x = CYR, y = n_mean)) +
geom_errorbar(aes(ymin=n_mean-se, ymax=n_mean+se), width=.2, color = "black") +
geom_point(color = "black", shape = 1, size = 2) +
geom_line(color = "black") +
scale_y_continuous(limits = c(0, 0.04), expand = expansion(mult = c(0, 0.05))) +
scale_x_continuous(breaks= years, labels = ~ rep("", length(.x))) +
annotate(geom = "text",
x = wet_pivot$CYR,
y = -Inf,
label = labs,
size = 8.8 / .pt,
vjust = 2.5) +
annotate(geom = "text",
x = wet_pivot$CYR,
y = -Inf,
label = wet_pivot$WYR,
size = 8.8 / .pt,
vjust = 4) +
# Titles
annotate(geom = "text",
x = -Inf,
y = -Inf,
label = c("CYR", "WYR"),
vjust = c(2.5, 4), hjust = 1,
size = 8.8 / .pt
) +
coord_cartesian(clip = "off") +
theme(
# Make extra space between axis ticks and axis title
axis.text.x.bottom = element_text(margin = margin(t = 8.8, b = 8.8))
)
Created on 2022-05-19 by the reprex package (v2.0.1)

How do I set legend element titles?

I am using code from this biostars post to get myself more acquainted with creating plots in ggplot. I am a bit stuck on setting the legend variables though
Is there a way to set the colour and control the number of breaks/dots in the legend (under numDEInCat)
term <-c("snoRNA binding", "preprophase band", "kinesin complex", "microtubule motor activity", "DNA replication")
fc <-runif(5, 1.00, 5.00)
padj_BH <-runif(5, 0.001, 0.05)
numDEInCat <-runif(5, 30, 300)
ggdata <- data.frame(term,fc,padj_BH, numDEInCat)
gg1 <- ggplot(ggdata,
aes(x = term, y = fc, size = numDEInCat, color = padj_BH)) +
expand_limits(y = 1) +
geom_point(shape = 16,inherit.aes = T) +
scale_size(range = c(2.5,12.5)) +
scale_color_gradient(low= "#ff0303",
high="#1e00b3")+ #colour for p value
xlab('') + ylab('Fold Enrichment') + #lavel fold enrichment axis
labs(
title = "Gene Ontology all",
subtitle = 'BH-adjusted',
caption = '',
color="Adjusted P-value", #label the aacolor
size="count") + #label dot size
theme_bw(base_size = 24) +
theme(
legend.position = 'right',
legend.background = element_rect(),
plot.title = element_text(angle = 0, size = 16, face = 'bold', vjust = 1),
plot.subtitle = element_text(angle = 0, size = 14, face = 'bold', vjust = 1),
plot.caption = element_text(angle = 0, size = 12, face = 'bold', vjust = 1),
axis.text.x = element_text(angle = 0, size = 12, face = 'bold', hjust = 1.10),
axis.text.y = element_text(angle = 0, size = 12, face = 'bold', vjust = 0.5),
axis.title = element_text(size = 12, face = 'bold'),
axis.title.x = element_text(size = 12, face = 'bold'),
axis.title.y = element_text(size = 12, face = 'bold'),
axis.line = element_line(colour = 'black'),
#Legend
legend.key = element_blank(), # removes the border
legend.key.size = unit(1, "cm"), # Sets overall area/size of the legend
legend.text = element_text(size = 14, face = "bold"), # Text size
title = element_text(size = 14, face = "bold")) +
coord_flip()
gg1
I think what you're looking for are guides(size = guide_legend(override.aes(BLABLA))) and scale_size(breaks = c(BLABLA))
gg1 +
guides(size = guide_legend(override.aes = list(colour = "red"))) +
scale_size(limits = c(1, 1000), breaks = c(10, 500, 1000))
Created on 2021-11-18 by the reprex package (v2.0.1)