I currently have a map that has plotted sites from 2 different data frames. I have red dots for one set and blue dots for another set. I can get the hover text to read from one of the data frames but how do i get it to read from another when hovering over the other color site?
here is my code so far
....Get the world polygon and extract UK
library(maps)
UK <- map_data("world") %>% filter(region=="UK")
png("JCMap.png")
JCMap <- ggplot() +
geom_polygon(data = UK, aes(x=long, y = lat, group = group), fill="grey", color = "dark grey",alpha=0.3) +
geom_point( data=sitesgeo, aes(x=long, y=lat), colour = 'blue', alpha = 0.5)+
geom_point( data=SCBenchmarks, aes(x=long, y=lat), size = 2, colour = 'red') +
theme_void() + ylim(50,59) + coord_map()+
theme(legend.position="none")+
ggtitle("Sites")+
theme(
plot.background = element_rect(fill = "#f5f5f2", color = NA),
panel.background = element_rect(fill = "#f5f5f2", color = NA),
plot.title = element_text(size= 16, hjust=0.1, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
)
print(JCMap)
JCMap
.....make it interactive!
library(plotly)
p=SCBenchmarks %>%
mutate( mytext=paste("Site: ", site_name, "\n", "Customers: ", claimant_key, sep="")) %>%
ggplot() +
geom_polygon(data = UK, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
geom_point(data=sitesgeo,aes(x=long, y=lat), colour = 'blue', alpha = 0.5) +
geom_point(aes(x=long, y=lat, text=mytext), colour = 'red', alpha = 1) +
scale_size_continuous(range=c(1,15)) +
scale_color_viridis(option="inferno", trans="log" ) +
scale_alpha_continuous(trans="log") +
theme_void() +
ylim(50,59) +
coord_map() +
theme(legend.position = "none")
p=ggplotly(p, tooltip="text")
p
Any help would be much appreciated
Cheers
I figured this out with a little help from a friend, probably not the most convenient way to do it but it works....see code below
######## plot
SCBenchmarks <- SCBenchmarks %>%
mutate( mytext=paste(site_name, "\n", "Customers: ", customer_key, "\n", "Customers per Person: ", Cust_Per_Person, "\n", sep=""))
Final <- Final %>%
mutate( mytext=paste(site_name, "\n", district_name,"\n", "Customers: ", Customer_Count, "\n", sep=""))
## Make the static plot call this text:
p <- ggplot() +
geom_polygon(data = UK, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
geom_jitter(data=Final,aes(x=long, y=lat, text=mytext), colour = 'blue', alpha = 0.5) +
geom_jitter(data=SCBenchmarks,aes(x=long, y=lat, text=mytext), colour = 'red', alpha = 1) +
scale_size_continuous(range=c(1,15)) +
scale_color_viridis(option="inferno", trans="log" ) +
scale_alpha_continuous(trans="log") +
theme_void() +
ylim(50,59) +
coord_map() +
theme(legend.position = "none")
p=ggplotly(p, tooltip="text")
p
Related
I would like to make my data have different colors for species and different patterns for sex. However, I can only set to make it different colors according to the sex. Here is my data,
data
This is how I run my script,
#making bar plot
library(readr)
library(ggplot2)
# loading and checking the data
data_summary <- read_csv("trial.csv")
print(data_summary)
# coloured barplot
ggplot(data_summary, aes(x = factor(species), y = mean, fill = sex)) +
geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9), width = 0.2, show.legend = FALSE) +
labs(x="", y="") + theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
theme(legend.position = c(0.1, 0.75)) + ylim(0, 80) +
scale_fill_manual(values=c("#870A30","#D3D3D3"))
This can be done using fill = interaction(..,..):
library(ggplot2)
ggplot(data_summary, aes(x = factor(species), y = mean, fill = interaction(species,sex))) +
geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9), width = 0.2, show.legend = FALSE) +
labs(x="", y="") +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
theme(legend.position = c(0.1, 0.75)) + ylim(0, 80) +
scale_fill_manual(values= c("#870A30", '#009E73', '#CC79A7', "#D3D3D3"))
An option could be using ggplot_build and add a vector of four colors (you change this to what you want) to the fill column of the bars layer like this:
library(ggplot2)
p <- ggplot(data_summary, aes(x = factor(species), y = mean, fill = sex)) +
geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9), width = 0.2, show.legend = FALSE) +
labs(x="", y="") + theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
theme(legend.position = c(0.1, 0.75)) + ylim(0, 80) +
scale_fill_manual(values=c("#870A30","#D3D3D3"))
q <- ggplot_build(p)
q$data[[1]]$fill <- c("#870A30","#D3D3D3", '#009E73', '#CC79A7')
q <- ggplot_gtable(q)
plot(q)
Created on 2023-01-02 with reprex v2.0.2
You can use ggpattern to get different patterns per sex and different colors per species:
library(ggplot2)
library(ggpattern)
ggplot(data_summary, aes(x = species, y = mean, fill = species, group = sex)) +
geom_col_pattern(position = "dodge", aes(pattern = sex),
pattern_fill = "white", pattern_color = "white",
pattern_angle = 45, show.legend = FALSE) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9),
width = 0.2, show.legend = FALSE) +
labs(x = NULL, y = NULL) +
theme_classic() +
theme(panel.border = element_rect(linewidth = 0.5, fill = NA)) +
ylim(0, 80) +
scale_fill_manual(values = c("#870A30" ,"#D3D3D3"))
There is a nice package called ggpattern which offers hatching for geoms. Unfortunately it is not available for the R version I am using.
But I would like to offer different alpha values for the fill color.
The alpha itself can defined like scale_alpha_manual(values = c(.5,1)).
library(ggplot2)
data_summary <- read.table(text = "
species,sex,mean,sd,tukey
species_a,female,67,4.17,a
species_b,male,62.2,4.8,a
species_b,female,61.3,6.43,a
species_a,male,49.7,16.2,a
", header = T, sep = ','
)
# coloured barplot
ggplot(data_summary, aes(x = factor(species), y = mean, fill = sex, alpha = species)) +
geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), position = position_dodge(0.9), width = 0.2, show.legend = FALSE) +
labs(x="", y="") + theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
theme(legend.position = c(0.1, 0.75)) + ylim(0, 80) +
scale_fill_manual(values=c("#870A30","#D3D3D3")) +
scale_alpha_manual(values = c(.5,1))
I have a bar graph (created using ggplot2 package) coming from one set of yearly data (with multiple y values)and I want to overlay on it data from another set of yearly data in the form of a line. Here is my code:
library (zoo)
require(ggplot2)
library(reshape)
library(Cairo)
library(reshape2)
x<-c(2000,2001,2002,2003,2004)
y1<-c(41,62,71,316,172)
y2<-c(3018,2632,2643,2848,2738)
y3<-c(3065,2709,2721,3192,2925)
dat1 <- data.frame(Year=x, y1, y2)
dat.m1 <- melt(dat1, id.vars='Year')
a<-ggplot(dat.m1, aes(Year, value)) +
geom_bar(width=0.6,aes(fill = variable),stat = "identity")+
xlab("Year") + ylab("Water Depth (mm)")+
theme(legend.position="top")+
theme(panel.background = element_rect(fill = 'white', colour = 'black'))+
theme(axis.text=element_text(size=13),axis.title=element_text(size=14))+
theme(legend.text=element_text(size=14))+
theme(plot.margin=unit(c(0.2,0.7,0.5,0.2),"cm"))+
guides(fill = guide_legend(title="", title.position="top", direction="horizontal"))
a
At this stage, bar plot is running nicely but when I tried to add line plot from different data frame as follow:
dat2 <- data.frame(Year=x, y3)
dat.m2 <- melt(dat2, id.vars='Year')
b<-ggplot(dat.m1, aes(Year, value)) +
geom_bar(width=0.6,aes(fill = variable),stat = "identity")+
geom_line(dat.m2, aes(x = x, y = y3), size = 1.5, color="red") +
xlab("Year") + ylab("Water Depth (mm)")+
theme(legend.position="top")+
theme(panel.background = element_rect(fill = 'white', colour = 'black'))+
theme(axis.text=element_text(size=13),axis.title=element_text(size=14))+
theme(legend.text=element_text(size=14))+
theme(plot.margin=unit(c(0.2,0.7,0.5,0.2),"cm"))+
guides(fill = guide_legend(title="", title.position="top", direction="horizontal"))
b
It did not work and I received this error message:
"Error in validate_mapping():
! mapping must be created by aes()
Run rlang::last_error() to see where the error occurred."
Anyone can help me to fix this issue? Also, any suggestion to add a line plot with each bar in the first data frame?
You need to add argument name data in geom_line(). Otherwise dat.m2 is received as mapping to the geom_line function.
dat2 <- data.frame(Year = x, y3)
dat.m2 <- melt(dat2, id.vars = 'Year')
b <- ggplot(dat.m1, aes(Year, value)) +
geom_bar(width = 0.6, aes(fill = variable), stat = "identity") +
geom_line(data = dat.m2, aes(x = x, y = y3), size = 1.5, color = "red") + # adding data argument name
xlab("Year") + ylab("Water Depth (mm)") +
theme(legend.position = "top") +
theme(panel.background = element_rect(fill = 'white', colour = 'black')) +
theme(axis.text = element_text(size = 13),
axis.title = element_text(size = 14)) +
theme(legend.text = element_text(size = 14)) +
theme(plot.margin = unit(c(0.2, 0.7, 0.5, 0.2), "cm")) +
guides(fill = guide_legend(
title = "",
title.position = "top",
direction = "horizontal"
))
b
I plot a scatter plot with ggplot() and use a certain color palette, namely 'Greens'. Basically I am very happy with the plot, but I would like to have a black border around each point. My code for the plot is:
p <- ggplot(data = df.dataCorrelation, aes(x = prod1, y = prod2)) +
geom_point(aes(color = year)) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
scale_color_brewer(palette = 'Greens') + # customized color palette
xlab(product1) +
ylab(product2) +
ggtitle("Correlation Scatter Plot (Pearson)") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
and provides the following graphic:
I know that I can draw black borders with the command:
geom_point(aes(color = year, fill = ?), color = "black", pch = 21),
but that doesn't work with my selected color palette because I don't know what to use in fill = ?
Try with this.
Here data for a reproducible example
library(dplyr)
product1 <- "product1"
product2 <- "product2"
df.dataCorrelation <- iris %>% rename(prod1 = Petal.Length,
prod2 = Petal.Width,
year = Species)
Here your code
library(ggplot2)
ggplot(data = df.dataCorrelation, aes(x = prod1, y = prod2)) +
geom_point(aes(fill = year), colour = "black", shape = 21, size = 3) +
geom_smooth(method = "lm", se = FALSE, color = "#007d3c") +
theme_classic() +
theme(legend.position = "none") +
theme(panel.background = element_blank()) +
scale_fill_brewer(palette = 'Greens') + # customized color palette
xlab(product1) +
ylab(product2) +
ggtitle("Correlation Scatter Plot (Pearson)") +
theme(plot.title = element_text(hjust = 0.5, face = "bold"))
NOTE that:
I wrote colour = "black"
I changed scale_colour_brewer to scale_fill_brewer
I wrote fill = year instead of colour = year
(I increased the size of the points only because I couldn't see the final result)
I am preparing a multiplot for with two y axes for Inc and Ratio.
I distinguished each plot with different colours to represent three regions.
There are three items I am not successful at:
I do have now, two lines with the same colour in each plot. I would like to change one of them to be dashed (Ratio one).
I need to add SE bars to Inc line (from Inc column)
I would like to add geom_points() so there are also points at the nodes where lines are connecting, only for aesthetic reasons.
This is as far as I get:
df <- data.frame(c(2009,2009,2009,2009,2010,2010,2010,2010,2011,2011,2011,2011,
2012,2012,2012,2012,2013,2013,2013,2013),
c("N","S","W","W","N","S","W","W","N","S","W","W","N","S","W","W",
"N","S","W","W"),
c("Luo","Aka","Opo","Mya","Luo","Aka","Opo","Mya",
"Luo","Aka","Opo","Mya","Luo","Aka","Opo","Mya",
"Luo","Aka","Opo","Mya"),
runif(20,0,1),runif(20,0,1),
runif(20,0,0.1))
colnames(df) <- c("Year","Region","District","Inc","Ratio","Inc_SE")
# Order of drawing in facet
df$District<- factor(df$District,
levels = c("Opo",
"Mya",
"Luo",
"Aka"))
p <- ggplot(data=df, aes(x = Year))
p <- p + geom_line(aes(y = Inc))
p <- ggplot(df, aes(x = Year, y=df$Inc))
p <- p + geom_line(aes(y = Inc))
p <- ggplot(df, aes(x = Year))
p <- p + geom_line(aes(y = Inc, colour = Region))
p <- p + theme_bw()+
theme(plot.title = element_text(hjust = 1))+
theme(legend.position="none")+
theme(axis.title.x = element_text(face ="bold", colour="black", size=11),
axis.text.x = element_text(angle=90, vjust=0.5, size=7, family = "serif"),
axis.title.y = element_text(face = "bold", colour = "black", size=10))
# adding Ratio
p <- p + geom_line(aes(y = Ratio, colour = Region,linetype = "dashed")) # here dashed is not recognised by R
# now adding the secondary axis
p <- p + scale_y_continuous(sec.axis = sec_axis(~.*1, name = "Ratio"))
p <- p + scale_colour_manual(values = c("blue", "red","black"))
p <- p +
theme_bw()+
theme(plot.title = element_text(hjust = 1))+
theme(legend.position="none")+
theme(axis.title.x = element_text(face ="bold", colour="black", size=11),
axis.text.x = element_text(angle=90, vjust=0.5, size=9, family = "serif"),
axis.title.y = element_text(face = "bold", colour = "black", size=10))
# Breaking down to separate graphs
p_facet = p + facet_wrap(~ df$District,
ncol = 2)
p_facet
You can try a tidyverse. The trick is to transform the data from wide to long (here I used gather). then you can easily add points, lines and Inc_SE as ribbon.
library(tidyverse)
df %>%
gather(k,v, -Year, -Region, -District, -Inc_SE) %>%
ggplot(aes(Year, v, group = k, color=Region, linetype=k)) +
geom_ribbon(data=. %>% filter( k == "Inc"),
aes(ymin=v-Inc_SE, ymax=v+Inc_SE),
alpha=0.2,color=NA,
show.legend = F) +
geom_line() +
geom_point(show.legend = F)+
scale_y_continuous(sec.axis = sec_axis(~.*1, name = "Ratio"))+
facet_wrap(~ District) +
labs(y="Inc") +
theme_bw() +
theme(legend.position = "bottom")
I'm trying to great a plot with one legend on the right side and one on the bottom. Both outside the map. I have tried a few suggestions but either both legends or neither legend moves.
library(ggthemes)
library(ggmap)
library(ggplot2)
d <- data.frame(McMap)
County_Mayo_Map <- get_map("MAP", zoom=9)
p <- ggmap(County_Mayo_Map)
p <- p + geom_point(data=d, aes(lat, lon)) +
geom_point(stat = "identity") +
geom_point(data = d, aes(color = Name), size = 5) +
scale_shape_manual(values=df$x) +
geom_point(data = d, aes(shape = Town), size = 4) +
labs(caption = ("SPM 8-19-17")) +
labs(title = "Title", subtitle = "Subtitle") +
ylab("Latitude") +
xlab("Longitude") +
coord_fixed(ratio = 1/1) +
theme(legend.background = element_rect(
fill ="lemonchiffon",
colour = "black",
size =1)) +
theme_solarized()