Server Error: Invalid plot index and many duplicate plots - r

I am not sure why, but it seems as if my code is plotting LOTS of plots in RStudio. I am new to R and RStudio so I can't figure out how many is being plotted, but I think there are duplicates, previous plots, and the plots I want, all within the Plots tab in RStudio. Also, when I try to scroll to see which plots are created, I am getting popups
I am expecting 5 plots for each state but it seems as though I am getting a lot more
library(ggplot2)
try(data('midwest', package='ggplot2'))
for (s in unique(midwest$state)) {
state_data = subset(midwest, state == s)
print(
ggplot(state_data, aes(x=county, y=percprof)) +
geom_bar(stat='identity') +
labs(title=paste(s)) +
xlab('Counties') + ylab('Percentage') +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
)
}

Your code runs fine for me. Try restarting R. It may be a server issue, but it's nothing wrong with your code.

Related

ggplot theme argument for axis arrows suddenly not working

I have a custom ggplot theme that I have been using for a while now. This week I started getting an error when making plots using this theme stating that plot.new has not been called yet
I've traced the error to an axis.line() argument which i've used before to turn my axis lines into arrows. I was able to reproduce the error below, but i'm confused why this is happening now. Does anyone know why this could be happening or possibly provide some alternatives to changing axis lines to arrows?
Eg:
library(ggplot2)
dat <- mtcars
ggplot(data = dat) +
geom_point(aes(x = wt, y = mpg)) +
theme(axis.line = element_line(color = "black", arrow = arrow(length = unit(0.3, "lines"), type = "closed")))
EDIT:
loading the graphics library (library(graphics)) fixed the issue temporarily. However knitting the markdown file produces the same error as above. It seems my example is not reproducing the error, however it's persisting on my computer even after re-installing RStudio AND updating all packages.

Is there a way I can add log gridlines to my graph with RStudio?

I'm currently trying to create a dose-response curve with Rstudio and I'm using the tidydrc package. I was wondering if there was a way I could add minor gridlines, since the x-axis is log.
Here's an image of what I've got so far
This is the code I've got so far:
tidydrc_plot(Nifedipinedrc,ed50=FALSE) +
scale_x_log10() +
geom_errorbar(aes(ymin=g$Nifedipine-g$SD, ymax=g$Nifedipine+g$SD, x=Nifedipinedrc[[1]][[1]]$d, y=Nifedipinedrc[[1]][[1]]$r)) +
ggtitle("graph") +
labs(x="Concentration", y= "Force")
I know it's an absolute mess of a code but I'm completely self taught and I feel like I've hit a bit of a brick wall with this because I don't actually understand a lot of the guides currently on stack.
Here is a function that you can use for the minor_breaks argument of log scales. The proposed function uses an unexported function from ggplot2, so I'm cheating a little bit. This probably only works well for log10 axis though and you might want to accentuate the major gridlines some more through the theme() setting.
library(ggplot2)
# A function factory for minor log breaks
minor_breaks_log <- function(base) {
# Prevents lazy evaluation
force(base)
# Wrap calculation in a function that the outer function returns
function(limits) {
ggplot2:::calc_logticks(
base = base,
minpow = floor(log(limits[1], base = base)),
maxpow = ceiling(log(limits[2], base = base))
)$value
}
}
ggplot(msleep, aes(bodywt, brainwt)) +
geom_point() +
scale_y_log10(minor_breaks = minor_breaks_log(10)) +
scale_x_log10(minor_breaks = minor_breaks_log(10))
#> Warning: Removed 27 rows containing missing values (geom_point).
Created on 2020-12-02 by the reprex package (v0.3.0)

Shiny app can't find an attribute in my dataset

I am plotting some attributes of my dataset. I have a weird issue: I have worked on my dataset for days and it all worked. Now I have put some parts of my work (the grafic parts) on a shiny app.
It is not working and gives me an error: he can't fine one of the attributes I have. But it can find the other two from the same db.
Error: ** Warning: Error in reorder: object "CompanyLocation" not found **
Can you help me please?
Edit: I have three plots. They have Identical code (I only changed the attributes), but only 2/3 are working. Here is the code of the not working one (server part).
library(dplyr)
singleLocation <- group_by(chocolate, CompanyLocation)
ratingLocation <- summarise(singleLocation, count=n(), ratingMedio=mean(Rating))
locationDesc<- arrange(ratingLocation, desc(ratingMedio))
library(ggplot2)
ggplot(locationDesc,aes(x=reorder(CompanyLocation, ratingMedio), y=ratingMedio)) +
geom_point(aes(size=count, colour=factor(ratingMedio)), alpha=1/2) + theme(
axis.text.x = element_text(angle = 90, hjust = 1) , legend.position="none") +
labs(x="Country", y="Chocolate Rating", main="Company Location & Rating")

Groups with fewer than two data points have been dropped. ggplot r

A couple of weeks ago, I drew a ggplot density plot in r. It worked fine. And then yesterday, I revisited and ran the same code. There was absolutely no change in the body of the code (only change in the Rmarkdown formatting like changing font size of texts, echo = FALSE, etc). I simply re-ran the same code and for some reason it does not work.
Here's the code for the dataset:
m_hospitals = m_hospitals %>% group_by(Provider.Name) %>% summarise(accSum =
sum(Average.Covered.Charges), atpSum = sum(Average.Total.Payments), ampSum =
sum(Average.Medicare.Payments), accMean = mean(Average.Covered.Charges),
atpMean = mean(Average.Total.Payments), ampMean =
mean(Average.Medicare.Payments))
#Take a sample
set.seed(1219)
sample_m_hospitals = m_hospitals[sample(nrow(m_hospitals), 30), ]
And here's the code for the plot that worked before but not anymore:
ggplot(data = sample_m_hospitals) +
aes(x = Provider.Name, y = accMean) +
geom_density(alpha = .75) + theme(axis.text.x = element_text(angle = 45,
hjust = 1))
It's giving me this message, "Groups with fewer than two data points have been dropped" * 30.
It is true that each of 30 rows only has 1 observation because they are summarised. Funny thing is, the message did not pop up before, did not drop any data points and worked fine. I even have the screenshot I took for the plot drawn. Here's the link: 1
One change I feel suspicious about is updating R (updated before re-plotting, 3.5.0 > 3.5.1) which erased all my libraries that I had to re-install all of them. But I'm not sure if the update has to do anything with this issue. It worked fine, but why is it suddenly not working? I don't understand.. Please help! I just wanna plot this in similar form however possible.
Contents updated as per you guys' comments:
Screenshots for devtools::session_info()
2 , 3
Screenshots for sample_m_hospitals
4 , 5
I had a similar issue which was resolved by converting columns. Numeric columns were being imported as strings.

Ggplot does not show plots in sourced function

I've been trying to draw two plots using R's ggplot library in RStudio. Problem is, when I draw two within one function, only the last one displays (in RStudio's "plots" view) and the first one disappears. Even worse, when I run ggsave() after each plot - which saves them to a file - neither of them appear (but the files save as expected). However, I want to view what I've saved in the plots as I was able to before.
Is there a way I can both display what I'll be plotting in RStudio's plots view and also save them? Moreover, when the plots are not being saved, why does the display problem happen when there's more than one plot? (i.e. why does it show the last one but not the ones before?)
The code with the plotting parts are below. I've removed some parts because they seem unnecessary (but can add them if they are indeed relevant).
HHIplot = ggplot(pergame)
# some ggplot geoms and misc. here
ggsave(paste("HHI Index of all games,",year,"Finals.png"),
path = plotpath, width = 6, height = 4)
HHIAvePlot = ggplot(AveHHI, aes(x = AveHHI$n_brokers))
# some ggplot geoms and misc. here
ggsave(paste("Average HHI Index of all games,",year,"Finals.png"),
path = plotpath, width = 6, height = 4)
I've already taken a look here and here but neither have helped. Adding a print(HHIplot) or print(HHIAvePlot) after the ggsave() lines has not displayed the plot.
Many thanks in advance.
Update 1: The solution suggested below didn't work, although it works for the answer's sample code. I passed the ggplot objects to .Globalenv and print() gives me an empty gray box on the plot area (which I imagine is an empty ggplot object with no layers). I think the issue might lie in some of the layers or manipulators I have used, so I've brought the full code for one ggplot object below. Any thoughts? (Note: I've tried putting the assign() line in all possible locations in relation to ggsave() and ggplot().)
HHIplot = ggplot(pergame)
HHIplot +
geom_point(aes(x = pergame$n_brokers, y = pergame$HHI)) +
scale_y_continuous(limits = c(0,10000)) +
scale_x_discrete(breaks = gameSizes) +
labs(title = paste("HHI Index of all games,",year,"Finals"),
x = "Game Size", y = "Herfindahl-Hirschman Index") +
theme(text = element_text(size=15),axis.text.x = element_text(angle = 0, hjust = 1))
assign("HHIplot",HHIplot, envir = .GlobalEnv)
ggsave(paste("HHI Index of all games,",year,"Finals.png"),
path = plotpath, width = 6, height = 4)
I'll preface this by saying that the following is bad practice. It's considered bad practice to break a programming language's scoping rules for something as trivial as this, but here's how it's done anyway.
So within the body of your function you'll create both plots and put them into variables. Then you'll use ggsave() to write them out. Finally, you'll use assign() to push the variables to the global scope.
library(ggplot2)
myFun <- function() {
#some sample data that you should be passing into the function via arguments
df <- data.frame(x=1:10, y1=1:10, y2=10:1)
p1 <- ggplot(df, aes(x=x, y=y1))+geom_point()
p2 <- ggplot(df, aes(x=x, y=y2))+geom_point()
ggsave('p1.jpg', p1)
ggsave('p2.jpg', p2)
assign('p1', p1, envir=.GlobalEnv)
assign('p2', p2, envir=.GlobalEnv)
return()
}
Now, when you run myFun() it will write out your two plots to .jpg files, and also drop the plots into your global environment so that you can just run p1 or p2 on the console and they'll appear in RStudio's Plot pane.
ONCE AGAIN, THIS IS BAD PRACTICE
Good practice would be to not worry about the fact that they're not popping up in RStudio. They wrote out to files, and you know they did, so go look at them there.

Resources