Object not being found when using ggplot2 in R - r

While creating a shot chart in R, I've been using some open source stuff from Todd W. Schneider's BallR court design (https://github.com/toddwschneider/ballr/blob/master/plot_court.R)
along with another Stack Overflow post on how to create percentages within hexbins (How to replicate a scatterplot with a hexbin plot in R?).
Both sources have been really helpful for me.
When I run the following lines of code, I get a solid hexbin plot of percent made for shots for the different locations on the court:
ggplot(shots_df, aes(x = location_y-25, y = location_x, z = made_flag)) +
stat_summary_hex(fun = mean, alpha = 0.8, bins = 30) +
scale_fill_gradientn(colors = my_colors(7), labels = percent_format(),
name = "Percent Made")
However, when I include the BallR court design code snippet, which is shown below:
ggplot(shots_df, aes(x=location_y-25,y=location_x,z=made_flag)) +
stat_summary_hex(fun = mean, alpha = 0.8, bins = 30) +
scale_fill_gradientn(colors = my_colors(7), labels=percent_format(),
name="Percent Made") +
geom_path(data = court_points,
aes(x = x, y = y, group = desc, linetype = dash),
color = "#000004") +
scale_linetype_manual(values = c("solid", "longdash"), guide = FALSE) +
coord_fixed(ylim = c(0, 35), xlim = c(-25, 25)) +
theme_court(base_size = 22)
I get the error: Error in eval(expr, envir, enclos) : object 'made_flag' not found, even though that the made_flag is 100% in the data frame, shots_df, and worked in the original iteration. I am lost on how to fix this problem.

I believe your problem lies in the geom_path() layer. Try this tweek:
geom_path(data = court_points, aes(x = x, y = y, z = NULL, group = desc, linetype = dash))
Because you set the z aesthetic at the top, it is still inheriting in geom_path() even though you are on a different data source. You have to manually overwrite this with z = NULL.

Related

Points to flags in ggplot2

I would like to change the dots in the next plot to the flag for the respective country. For this I know that geom_flag() could works, but... not for me but I got stuck with this error message:
Error in grobify(picture, x = x, y = y, width = width, height = height, :
object '.flaglist' not found
This is my code:
ggplot(df, aes(lenght, Ponto.Caspian)) +
geom_point()+ ggflags::geom_flag(aes(x = longitude, y = latitude+0.5, country = country))
maybe also geom_image() could work but I don't know how to link the flag with the country column...or How to use an image as a point in ggplot?, but I don't understand the process
This my desire plot, but changing dots to flags:
ggplot(df, aes(lenght, Ponto.Caspian)) +
geom_point(aes(colour = factor(country)))+
scale_fill_brewer(palette = "Set3")+ scale_x_continuous(breaks = seq(10, 40, by = 5))+
scale_y_continuous(breaks = seq(0, 16, by = 1))+
theme_classic2() + theme_cleveland()+ geom_smooth(method = "lm", alpha=0.2)+
stat_cor(label.x = 2, label.y = 1)
This is my data:
https://drive.google.com/drive/folders/1qR2mUdrpStOYBmxajc_F4nxS_qf-4bzf?usp=sharing
thanks in advance
It seems to work for me if I convert your countries to two-character ISO codes (which is what the example at https://github.com/jimjam-slam/ggflags uses).
I also had to load the ggflags library, rather than using ggflags::geom_flag
For example, using the countrycode package:
df$iso_code <- tolower(countrycode(df$country, origin = 'country.name', destination = 'iso2c'))
ggplot(df, aes(lenght, Ponto.Caspian)) +
geom_point() +
geom_flag(aes(x = longitude, y = latitude+0.5, country = iso_code))

Unable to add legend to economic time series chart

I'm attempting to add a legend to a time series chart and I've so far been unable to get any traction. I've provided the working code below, which pulls three economic data series into one chart and applies several changes to get in a format/overall aesthetic that I'd like. I should also add that the chart is graphing the y/y change of quarterly data sets.
I've only been able to find examples of individuals using scale_colour_manual to add a legend - I've provided code that I put together below.
Ideally, the legend just needs to appear to the right of the graph with the color and line chart.
Any help would be greatly appreciated!
library(quantmod)
library(TTR)
library(ggthemes)
library(tidyverse)
Nondurable <- getSymbols("PCND", src = "FRED", auto.assign = F)
Nondurable$chng <- ROC(Nondurable$PCND,4)
Durable <- getSymbols("PCDG", src = "FRED", auto.assign = F)
Durable$chng <- ROC(Durable$PCDG,4)
Services <- getSymbols("PCESV", src = "FRED", auto.assign = F)
Services$chng <- ROC(Services$PCESV, 4)
ggplot() +
geom_line(data = Nondurable, aes(x = Index, y = chng), color = "#5b9bd5", size = 1, linetype = "solid") +
geom_line(data = Durable, aes(x = Index, y = chng), color = "#00b050", size = 1, linetype = "longdash") +
geom_line(data = Services, aes(x = Index, y = chng), color = "#ed7d31", size = 1, linetype = "twodash") +
theme_tufte() +
scale_y_continuous(labels = percent, limits = c(-0.01,.09)) +
xlim(as.Date(c('1/1/2010', '6/30/2019'), format="%d/%m/%Y")) +
labs(y = "Percent Change", x = "", caption = "Seasonally Adjusted Annual Rate. Retrieved from FRED & U.S. Bureau of Economic Analysis") +
ggtitle("Year-over-Year Spending Trend Changes of the US Consumer") +
scale_colour_manual(name = 'Legend',
guide = 'legend',
values = c('Nondurable' = '#5b9bd5',
'Durable' = '#00b050',
'Services' = '#ed7d31'),
labels = c('Nondurable',
'Durable',
'Services'))
I receive the following warning messages when I run the program (the chart still plots though).
Warning messages:
1: Removed 252 rows containing missing values (geom_path).
2: Removed 252 rows containing missing values (geom_path).
3: Removed 252 rows containing missing values (geom_path).
There are two reasons you are receiving this error:
The bulk are being removed because of your limits. When you use xlim() or scale_y_continuous(..., limits = ...) ggplot removes the values beyond these limits from your data before plotting and displays that warning as an FYI. After commenting out both of those lines, you will still see a message about removed values but a much smaller number. This is becuase
you have NA values in the first 4 rows of column chng. This is true in all 3 datasets.
For the scales to show, you need to put something differentiating the lines in the aes() as in aes(..., color = "Nondurable"). See if this solution works for you:
ggplot() +
geom_line(data = Nondurable, aes(x = Index, y = chng, color = "Nondurable"), size = 1, linetype = "solid") +
geom_line(data = Durable, aes(x = Index, y = chng, color = "Durable"), size = 1, linetype = "longdash") +
geom_line(data = Services, aes(x = Index, y = chng, color = "Services"), size = 1, linetype = "twodash") +
theme_tufte() +
labs(
y = "Percent Change",
x = "",
caption = "Seasonally Adjusted Annual Rate. Retrieved from FRED & U.S. Bureau of Economic Analysis"
) +
ggtitle("Year-over-Year Spending Trend Changes of the US Consumer") +
scale_colour_manual(
name = "Legend",
values = c("#5b9bd5","#00b050","#ed7d31"),
labels = c("Nondurable", "Durable", "Services"
)
) +
scale_x_date(limits = as.Date(c("2010-01-01", "2019-02-01")))

geom_text / geom_label with the bquote function

My data :
dat <- data_frame(x = c(1,2,3,4,5,6), y = c(2,2,2,6,2,2))
I wish to display this expression beside the point (x=4,y=6) :
expression <- bquote(paste(frac(a[z], b[z]), " = ", .(dat[which.max(dat$y),"y"] %>% as.numeric())))
But, when I am using this expression with ggplot :
ggplot() +
geom_point(data = dat, aes(x = x, y = y)) +
geom_label(data = dat[which.max(dat$y),], aes(x = x, y = y, label = expression))
I get this error message :
Error: Aesthetics must be either length 1 or the same as the data (1): label
You could use the following code (keeping your definitions of the data and the expression):
Not related to your question, but: it is always better to define aesthetics in the ggplot-call and get it reused in the subsequent function calls. If needed, you may override the definitions, like done below in geom_label
ggplot(data = dat, aes(x = x, y = y)) +
geom_point() +
geom_label(data = dat[4,], label = deparse(expression), parse = TRUE,
hjust = 0, nudge_x = .1)
hjust and nudge_x are used to position the label relative to the point. One could argue to use nudge_y as well to get the whole label in the picture.
yielding this plot:
Please let me know whether this is what you want.

Doing a heatmap on ggmap in R based on % and not line entries

I have a dataset with the ff columns: (1) latitude of locations; (2) longitude; (3) population_count; (4) sample_count; (5) sample_perc (sample/ pop).
I need to visualise the sample_perc (col 5) over the ggmap output of the city as a heatmap. The problems I'm encountering are:
Not all coordinates in the map are relevant, and hence do not have data
Heatmap (geom_density) uses entries (rows) in the data and can't do aggregate (as far as I know)
Code:
amsmap <- get_map(location="amsterdam", zoom=14)
ggmap(amsmap) +
geom_density2d(data = dummy$sample_perc,
aes(x =request_lng, y = request_lat), size = 0.3) +
stat_density2d(data = dummy$sample_perc,
aes(x = request_lng, y = request_lat, fill = ..level..,
alpha = ..level..), size = 0.01, bins = 16, geom = "polygon") +
scale_fill_gradient(low = "green", high = "red") +
scale_alpha(range = c(0, 0.3), guide = FALSE)
error: ggplot2 doesn't know how to deal with data of class factor
How can I successfully do this? Help please.

Scatterplot: Error in FUN(X[[i]], ...) : object 'Group' not found

I'm trying to plot some data using ggplot and I'm having some problems with the significant lines and asterisk.
This is the code I am using:
p <- ggplot(Hematoxilin_tumor_necrosis, aes(x=total, y=necro, colour = Group))+
labs(y="Necrotic area",x="Total area")+
theme_minimal()
path = data.frame(x=c(78,79,79,78),y=c(22,22,34,34))
p + geom_point(size=0.7)+
geom_smooth(method=lm, se = F, size=0.8) +
scale_color_manual(values=c("#999999","#333333"))+
#Adding asterisks
geom_path(data = path, aes(x = x,y = y)) +
annotate("text",x = 80, y = 27, label="*", cex=7)
Which gives me the following error:
Error in FUN(X[[i]], ...) : object 'Group' not found
I know that the problem is in the geom_path(data = path, aes(x = x,y = y)) but I am kind of lost. I am new in ggplot so I expect some simple problem.
Any advice?
aesthetics are inherited by default. The geom_path is trying to look for the Group variable on the path dataset to get the color. You should use inherit.aes = FALSE on the geom_path:
geom_path(data = path, aes(x = x,y = y), inherit.aes = FALSE )

Resources