Shiny app can't find an attribute in my dataset - r

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")

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.

Plotting data frame in R using usmap library

I'm new to R and I'm trying to plot a data frame of county values using the usmap library.
I have a dataset containing all the FIPS (county codes) for a particular region and the data (deaths) that I want to show on the map.
This is my first R script so what I'm trying to accomplish is likely pretty easy and I just have no idea what I'm doing.
I'm pretty sure the error I'm receiving is because I haven't specified any kind of coloring to apply to the data? I'm unsure.
Here's my code - note that I'm trying to initially just plot one frame of data (a particular date):
library(usmap)
library(ggplot2)
library(RColorBrewer)
#set working directory
setwd("C:/Users/Name/Documents/RScripts/")
#input data from file separated by commas
usa.dat <- read.csv("covid.csv", header = T)
#Start at 1/22/2020
#End at 10/8/2021
plot_usmap(regions = "counties",
data=usa.dat$countyFIPS,
values=usa.dat$X1.22.2020,
) +
theme(panel.background = element_rect(color = "black", fill = "black"))
Here's the data:
The error I'm getting is Error in if (is.null(geom_args[["fill"]]) & nrow(data) == 0) { : argument is of length zero
When I remove the data/values lines from the function, I get a map that looks like this:
Any help is greatly appreciated!
Ideally, I'd like to animate each frame of the data with color scales; if you guys can help me with that, I'd appreciate it!
Edit:
Okay so, I've been working on this for awhile and I managed to get it working. I have no idea how to update the color scales/gradients that are used, however.
I got it to loop through the data and save a bunch of plots, so that's pretty awesome! Just need to figure out how to change the colors/scales if anyone can help!
I got it figured out (with some help from Ben!)
library(usmap)
library(ggplot2)
library(viridis)
library(RColorBrewer)
library(stringr)
library(stringi)
#set working directory
setwd("C:/Users/Tyrael/Documents/RScripts/")
#input data from file separated by commas
usa.dat <- read.csv("ccovid.csv", header = T)
for (i in 2:ncol(usa.dat)) {
da <- data.frame(fips=usa.dat$countyFIPS,val=usa.dat[,i])
da$val <- cut(da$val,breaks=c(0,100,500,1000,5000,20000,30000),labels=c("1-100","100-500","500-1K","1K-5K","5K-20K","20K-30K"))
theDate <- substr(names(usa.dat)[i],2,100)
plot_usmap(regions = "counties",
data=da,
values="val"
) +
labs(title=paste("Covid-19 Deaths ",str_replace_all(theDate,"\\.","/"),sep='')) +
scale_fill_viridis(name="Deaths",discrete=TRUE,na.translate=F) +
theme(panel.background = element_rect(color = "#101010", fill = "#101010"))
ggsave(paste(sprintf("%03d",i),".png",sep=''))
}
This splits everything up into a legend that looks like this:
The files are output in sequential order and, as a bonus, I'll show how to combine in ffmpeg:
ffmpeg -framerate 15 -i "C:\Users\Tyrael\Documents\RScripts\vpublish\%03d.png" -codec copy out.mkv
And to get it into .mp4 format:
ffmpeg -i out.mkv -codec copy out.mp4
Results: https://www.youtube.com/watch?v=-z3LL5j__es

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.

Server Error: Invalid plot index and many duplicate plots

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.

ggpairs() correlation values without gridlines

I have this code that generates the plot below.
library(ggplot2)
library(GGally)
data(iris)
ggpairs(data = iris[, 1:4], axisLabels = "none", switch = "both")
I'd like to do three things with this plot: 1) remove the gridlines in the correlation windows; 2) increase font size of the x-y axes labels; and 3) make these label-backgrounds white (instead of gray). The first question was addressed about 4 years ago here and here, and it seems one would need to either rebuild GGally package, or use a custom code from GitHub. Both options are pretty heavy for a newbie like me, and I am wondering if someone has figured out an easier method by now. I have not found my 2nd and 3rd questions addressed anywhere.
Thanks.
The first request can be handled by:
+theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
The size of the axis labels (which are really in "strips" can be handled with this additional arguemnt to theme:
... , strip.text = element_text(size = 5))

Resources