ggplot geom_bar with errors not printing - ggplot2

Assigning means and se to a data frame and trying to construct geom_bar with error bars for 2 experimental treatments across two genders
library(ggplot2)
dff <- data.frame(group=c('NSI','NSI','SI','SI'),
gender = c('Female','Male','Female','Male'),
mean.Score =c(3.41,3.3,2.63,3.32),
se =c(1.92,2.03,1.73,2.21))
dff$group <- as.factor(dff$group)
dff$gender <- as.factor(dff$gender)
p <- ggplot(dff,aes(x= group,y=mean.Score,fill=gender))+
scale_fill_manual(values = c("#F34444", "#0066CC"))+
geom_bar(position = 'dodge',stat = 'identity',width=1.8)+
geom_errorbar(aes(ymin=mean.Score-se, ymax=mean.Score+se),
width=.2,
position=position_dodge(1.8))+
theme(plot.title = element_text(size = 10,hjust = 0.9))+
scale_x_discrete(limits=c('NSI','NSI','SI','SI'))+
ggtitle("Performance by Treatment & Gender")
plot(p)
Two treatments: NSI and SI. Across two genders: Female and Male; data is corresponding mean performance and standard error of that performance. Assigning to a data frame and trying to plot a histogram with error bars of the data. Code executes fine in the window, but then nothing shows up in the Plot window. Thanks for any help for a relative newbie!
Mary

probably go to tools > global options > pane layout, and make sure the plot is checked for the console window
example of where to check in rstudio

Related

How to plot several coordinates from pymongo plotly and mapbox

I'm working in a project in which i need to plot several coordinates from a mongodb query, i can plot a single result and works awesome, but i need to figure out how to plot several coordinates from the query, the query contains the info needed but i don;t know how to iterate correctly in the result file i think that's my problem , i'm running on circles now so i need some help .
Code that works for a single result :
countE2 = mydb.results.find({"d.latitude":{"$gt":0},"d.longitude":{"$gt":0}},{"d.latitude":1, "d.longitude": 1,"a":1,"u.Server":1}).limit(10).sort('t', pymongo.DESCENDING)
for resultado in countE2:
lat = resultado["d"]["latitude"]
lon = resultado["d"]["longitude"]
ip = resultado["a"]
server = resultado["u"]["Server"]
us_cities = [lat,lon,ip,server]
y = us_cities
print(y)
fig = px.scatter_mapbox(y,lat=[y[0]], lon=[y[1]],hover_name=[y[2]],hover_data=[[y[3]],[y[3]]],color_discrete_sequence=["green"], zoom=3, height=1000)
print(fig)
fig.update_layout(mapbox_style="dark", mapbox_accesstoken=token)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
Please consider that the query returns several results ,in this case countE.
Thanks

How to display centroids for categorical variables instead of arrows using function ggord?

I really can’t figure out how to display just the centroids for my categorical variables using the function ggord. If anybody could help me, that would be great.
Here is an example of what I’m trying to achieve using the dune data set:
library(vegan)
library (ggord)
library(ggplot2)
ord <- rda(dune~Moisture+ Management+A1,dune.env)
#first plot
plot(ord)
# second plot
ggord(ord)
#I tried to add the centroids, but somehow the whole plot seems to be differently scaled?
centroids<-ord$CCA$centroids
ggord(ord)+geom_point(aes(centroids[,1],centroids[,2]),pch=4,cex=5,col="black",data=as.data.frame(centroids))
In the first plot only the centroids (instead of arrows) for moisture and management are displayed. In the ggord plot every variable is displayed with an arrow.
And why do these plots look so different? The scales of the axes is totally different?
Something like this could work - you can use the var_sub argument to retain specific predictors (e.g., continuous), then just plot others on top of the ggord object.
library(vegan)
library(ggord)
library(ggplot2)
data(dune)
data(dune.env)
ord <- rda(dune~Moisture+ Management+A1,dune.env)
# get centroids for factors
centroids <- data.frame(ord$CCA$centroids)
centroids$labs <- row.names(centroids)
# retain only continuous predictors, then add factor centroids
ggord(ord, var_sub = 'A1') +
geom_text(data = centroids, aes(x = RDA1, y = RDA2, label = labs))

Facet_grid with all panels with a free_y

I have a 6x6 grid (sites along the side and year along the top), showing abundance (y) over time(x).
I have used facet_grid to build the plot, using free_y. This has plotted a figure with each row having a shared y axis. I need to have a free_y for all the panels individually and I know that facet_grid doesnt allow this, while facet_wrap does. I would like to use facet_grid becuase it keeps the order of the panels, with columns for each year, and rows for each site.
I've tried using the lemon package with the facet_rep_grid function but this hasn't worked. Does anyone know how I can free_y across all the panels seperately?
Thanks
facet_wrap does this, and is what I use, although it does mean you have the faceting value as a title for each individual facet, which can be a pain.
ggplot(mpg, aes(displ, hwy, colour = as.factor(cyl))) +
geom_point() +
facet_wrap(year ~ drv,
scales = "free_y")
One suggestion is to use ggh4x::facet_grid2() to set independent y scales. (Disclaimer: I'm the author of ggh4x). Example with standard dataset below:
library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = as.factor(cyl))) +
geom_point() +
ggh4x::facet_grid2(vars(year), vars(drv),
scales = "free_y", independent = "y")
Created on 2022-03-11 by the reprex package (v0.3.0)
Another solution would be facet_rep_grid in the lemon package.
Sample code:
#install.packages("lemon")
library(lemon)
library(ggplot2)
ggplot(df)+
geom_line(aes(x=time, y=abundance, color=sites))+
lemon::facet_rep_grid(year~sites,
scales="free",
repeat.tick.labels = "all")+
theme(panel.background = element_blank(),
axis.line = element_line(size=0.5))+
labs(x="Time", y="Abundance", fill="Sites")+
theme_minimal()
Plot:

Zooming a pherical projection in matplotlib

I need to display a catalogue of galaxies projected on the sky. Not all the sky is relevant here, so I need to center an zoom on the relevant part. I am OK with more or less any projection, like Lambert, Mollweide, etc. Here are mock data and code sample, using Mollweide:
# Generating mock data
np.random.seed(1234)
(RA,Dec)=(np.random.rand(100)*60 for _ in range(2))
# Creating projection
projection='mollweide'
fig = plt.figure(figsize=(20, 10));
ax = fig.add_subplot(111, projection=projection);
ax.scatter(np.radians(RA),np.radians(Dec));
# Creating axes
xtick_labels = ["$150^{\circ}$", "$120^{\circ}$", "$90^{\circ}$", "$60^{\circ}$", "$30^{\circ}$", "$0^{\circ}$",
"$330^{\circ}$", "$300^{\circ}$", "$270^{\circ}$", "$240^{\circ}$", "$210^{\circ}$"]
labels = ax.set_xticklabels(xtick_labels, fontsize=15);
ytick_labels = ["$-75^{\circ}$", "$-60^{\circ}$", "$-45^{\circ}$", "$-30^{\circ}$", "$-15^{\circ}$",
"$0^{\circ}$","$15^{\circ}$", "$30^{\circ}$", "$45^{\circ}$", "$60^{\circ}$",
"$75^{\circ}$", "$90^{\circ}$"]
ax.set_yticklabels(ytick_labels,fontsize=15);
ax.set_xlabel("RA");
ax.xaxis.label.set_fontsize(20);
ax.set_ylabel("Dec");
ax.yaxis.label.set_fontsize(20);
ax.grid(True);
The result is the following:
I have tried various set_whateverlim, set_extent, clip_box and so on, as well as importing cartopy and passing ccrs.LambertConformal(central_longitude=...,central_latitude=...) as arguments. I was unable to get a result.
Furthermore, I would like to shift RA tick labels down, as they are difficult to read with real data. Unfortunately, ax.tick_params(pad=-5) doesn't do anything.

How to make a stacking bar using ggplot?

I have got this dataset. I am trying to do a stacking bar graph with proportions using ggplot for this data:
I am not really sure how to manipulate it into tables first! I know, I just started learning R, two weeks ago and I'm kind of stuck. I made a similar graph before. I attached it here.
I'm not sure if I got your question right, but I'll try to answer it. I see that this is your first question in Stack Overflow, so I'd advise you to post a minimal reproducible example on your next question.
1) "I am not really sure how to manipulate it into tables first!"
Copy the data into an excel file, save it as csv and import into R with base R command.
df <- read.csv('your_data.csv')
2) " do a stacking bar graph with proportions"
Your problem is very similar to the one mentioned in this question. Make sure to check it out, but I've already adapted the code below, see if it works.
library(ggplot2)
library(dplyr)
library(tidyr)
df <- read.csv('your_data.csv')
# Add an id variable for the filled regions and reshape
dfm <- df %>%
mutate(Domain = factor(row_number()) %>%
gather(variable, value, -Domain)
ggplot(dfm, aes(x = variable, y = value, fill = Domain)) +
geom_bar(position = "fill",stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity"
scale_y_continuous(labels = scales::percent_format())