Change axis labels in ggeffects plot - ggplot2

Is there any way to change legends/axis labels/tick marks in the plot( ) function for visualising model predictions in ggeffects? I can't find any mention of this in the function documentation, but it seems like such a bizarre thing to leave out ... ?

Thanks to user teunbrand - I hadn't realised you could add additional elements to ggeffects::plot() using as you would in ggplot( ) - adding + labs(title = "New title") etc worked!

Related

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

Draw multiple arrows using plotly python

There is an example about multiple annotations, it simply duplicate the go.layout.Annotation() to draw 2 arrows.
But I need to draw more than 100+ arrows, I don't know how.
The go.layout.Annotation() is tuple type and accepts dict() for each arrow, is there any easy way to add more dict() to tuple() ?
Thank you.
I solved my own question.
fig.layout.annotations accepts list, parameters of each arrow is a dict(). So the idea is to create a list of many dict(), and then use fig.update_layout(annotations = list) to draw multiple arrows.
the dict() for each arrow looks like this:
arrow = go.layout.Annotation(dict(
x= x_end,
y= y_end,
xref="x", yref="y",
text="",
showarrow=True,
axref = "x", ayref='y',
ax= x_start,
ay= y_start,
arrowhead = 3,
arrowwidth=1.5,
arrowcolor='rgb(255,51,0)',)
)
the list for multiple arrows can be easily created like this:
list = list + [dict()]
Then, update the fig:
fig.update_layout(
annotations= list_of_all_arrows,)
If all arrows are in time series, this is the final result:

Add Marker Annotations for Seaborn regplot

This is my first question on the site, however I've spent a lot of time finding valuable answers here!
I've searched all over the site, and can't find a good solution to my problem, hopefully someone can help! I have a pandas database that I've created a regplot, however I'd really like to add annotations for each marker based on another column.
Here is the code for my existing plot:
fig, ax = plt.subplots()
fig.set_size_inches(8,5)
sns.regplot(x=brakev["Curb_Weight"], y=brakev["Braking_60_0"])
sns.regplot(x=brakev["Curb_Weight"], y=brakev["Braking_60_0"], fit_reg=False)
Here is the diagram: regplot
. I found a proposal on the Python Graph Gallery (and others on Stack Overflow), but I'm struggling to get it to work:
for line in range(0,df.shape[0]):
p1.text(df.x[line]+0.2, df.y[line], df.group[line], horizontalalignment='left', size='medium', color='black', weight='semibold')
I'd like to add an annotation from the column 'Model' next to each marker. I'm less concerned about the position, color, font size at the moment, but that would also be helpful.
Here is the brakev.head() for my database:
brakev.head()
Model Curb_Weight Braking_60_0
0 Transit Connect 3580.0 132.0
1 NV200 3690.0 129.0
2 Sprinter 3710.0 132.0
3 Express 3620.0 135.0
4 Transit 3960.0 136.0
Sorry if this is a duplication, (I'm sure it is, but I can't find it!!). Thanks for the help!
I was able to find a solution! The key was to first store each of the x, y, and label elements into a list:
Curb_Weight = brakev.Curb_Weight.tolist()
Braking_60_0 = brakev.Braking_60_0.tolist()
Model = brakev.Model.tolist()
After this, the proposed solution was relatively easy to implement:
fig, ax = plt.subplots()
fig.set_size_inches(20,12)
sns.regplot(data=brakev, x='Curb_Weight', y='Braking_60_0')
p1 = sns.regplot(data=brakev, x='Curb_Weight', y='Braking_60_0',fit_reg=False,marker='o',scatter_kws={'s':50})
for line in range(0,brakev.shape[0]):
p1.text(Curb_Weight[line]+1.8, Braking_60_0[line], Model[line],
horizontalalignment='left',size='medium',color='black',weight='semibold')
The result includes the annotation label next to the markers, and is relatively legible excluding a few overlaps:
Diagram
If anyone has suggestions for optimization, or ideas how to "flip" the orientation of the label when another marker is within a specific range to avoid the overlap, let me know!

change matplotlib data in gui

I've developed an gui with python pyqt. There I have a matplotlib figure with x,y-Data and vlines that needs to change dynamically with a QSlider.
Right now I change the data just with deleting everything and plot again but this is not effective
This is how I do it:
def update_verticalLines(self, Data, xData, valueSlider1, valueSlider2, PlotNr, width_wg):
if PlotNr == 2:
self.axes.cla()
self.axes.plot(xData, Data, color='b', linewidth=2)
self.axes.vlines(valueSlider1,min(Data),max(Data),color='r',linewidth=1.5, zorder = 4)
self.axes.vlines(valueSlider2,min(Data),max(Data),color='r',linewidth=1.5, zorder = 4)
self.axes.text(1,0.8*max(Data),str(np.round(width_wg,2))+u"µm", fontsize=16, bbox=dict(facecolor='m', alpha=0.5))
self.axes.text(1,0.6*max(Data),"Pos1: "+str(round(valueSlider1,2))+u"µm", fontsize=16, bbox=dict(facecolor='m', alpha=0.5))
self.axes.text(1,0.4*max(Data),"Pos2: "+str(round(valueSlider2,2))+u"µm", fontsize=16, bbox=dict(facecolor='m', alpha=0.5))
self.axes.grid(True)
self.draw()
"vlines" are LineCollections in matplotlib. I searched in the documentation but could not find any hint to a function like 'set_xdata' How can I change the x value of vertical lines when they are already drawn and embedded into FigureCanvas?
I have the same problem with changing the x and y data. When trying the known functions of matplotlib like 'set_data', I get an error that AxisSubPlot does not have this attribute.
In the following is my code for the FigureCanvas Class. The def update_verticalLines should only contain commands for changing the x coord of the vlines and not complete redraw.
Edit: solution
Thanks #Craigular Joe
This was not exactly how it worked for me. I needed to change something:
def update_verticalLines(self, Data, xData, valueSlider1, valueSlider2, PlotNr, width_wg):
self.vLine1.remove()
self.vLine1 = self.axes.vlines(valueSlider1,min(Data), max(Data), color='g', linewidth=1.5, zorder = 4)
self.vLine2.remove()
self.vLine2 = self.axes.vlines(valueSlider2,min(Data), max(Data), color='g', linewidth=1.5, zorder = 4)
self.axes.draw_artist(self.vLine1)
self.axes.draw_artist(self.vLine2)
#self.update()
#self.flush_events()
self.draw()
update() did not work without draw(). (The old vlines stayed)
flush_events() did some crazy stuff. I have two instances of FigureCanvas. flush_events() caused that within the second instance call the vlines moved with the slider but moved then back to the start position.
When you create the vlines, save a reference to them, e.g.
self.my_vlines = self.axes.vlines(...)
so that when you want to change them, you can just remove and replace them, e.g.
self.my_vlines.remove()
self.my_vlines = self.axes.vlines(...)
# Redraw vline
self.axes.draw_artist(self.my_vlines)
# Add newly-rendered lines to drawing backend
self.update()
# Flush GUI events for figure
self.flush_events()
By the way, in the future you should try your best to pare down your code sample to just the essential parts. Having a lot of unnecessary sample code makes it hard to understand your question. :)

Adding maths function in ggplot annotation

I have a density plot using ggplot and I have a mathematical function I want to add on the graph using +annotate() or something similar, but I am not sure how to do this.
The symbol I want in latex code is:
$f_{\epsilon}(|R_{i}|)$
Thanks for any help :)
try this,
# install.packages("latex2exp")
library(latex2exp)
test <- TeX("$f_{\\epsilon}(|R_{i}|)$")
library(grid)
grid.newpage()
grid.text(test, gp = gpar(cex=4))