How to put text in figure using matplotlib in python - python

I am trying to plot multiple figures in a loop using matplotlib in python3. For every element in loop I draw the actual curve and Fitted curve. Here is the code that I have written:
plt.figure()
plt.plot(t, y,'g--',label="data")
plt.ylabel("Rate")
plt.xlabel("Time")
plt.title("{},{},{}".format(a,b,c),fontsize=8)
plt.text(0.8,0.8,"R-sq:"+str(round(r_squared,2)),fontsize=8)
plt.text(0.8,0.7,"decay:"+str(round(1/(12*fit_b),2)),fontsize=8)
plt.text(40.1,1.0,"#Cohort:"+str(C),fontsize=8)
plt.text(40.1,0.9,"Samples:"+str(int(S)),fontsize=8)
plt.grid()
plt.plot(t, yhat, 'b--',label='Fitted Function:\n $y = %0.4f e^{%0.4f t} $' % (fit_a, fit_b))
plt.legend(bbox_to_anchor=(0.4, 0.4), fancybox=True, shadow=True) #1.4, 1.1
name="./fig_weight/{}__{}__{}.png".format(a,b,c)
plt.savefig(name)
plt.show()
I am trying to put R-squared, Decay value and several other things in figure so that it is easy to visualize. For some of the plots alignment is fine but for others the text goes outside plot area.
I am running the same code for different iteration.
How to fix it?
Here are the plots:

You use plt.text location values with fixed numbers but your axis range is changing. One option is to plot locations based on your data, for example the last [-1] or middle [int(t.shape[0]/2.)] element on your curve with a shift tshift to offset the text, e.g.
plt.text(t[-1]+tshift, y[-1]+tshift,"R-sq:"+str(round(r_squared,2)),fontsize=8)

Related

Matplotlib | Python | Plotting figure A and then plotting another figure B on top of figure A

The fragment of code below plots a figure based on two arrays of floats
plt.scatter(t, h)
plt.xlabel("time")
plt.ylabel("height")
plt.show()
Then, after defining a function y(t), I need to add the following on top of the last plot:
plt.plot(t, y(t), 'r')
plt.show()
However, the code above generates two separate plots. I've noticed that if I comment out the first plt.show(), I'll get the second figure I am looking for. But is there a way to show them both?
I was expecting one plot and then another plot on top of the second one; however the second plot is shown as a new one
plt.show() draws your figure on screen.
So, you need to remove the first plt.show() from your code.
If you remove the first plt.show() you should see the joint plot. The first plt.scatter just produces points on the joints of the line.
import numpy as np
import matplotlib.pyplot as plt
t = np.random.random(10)
h = np.random.random(10)
plt.scatter(t, h)
plt.plot(t, h, 'r')
plt.show()
The scatter plot is just the blue dots

Python axis scaling in matplotlib

I am trying to make my plots a bit more readable and have come across a feature where the axes are automatically scaled by factors of tens (so instead of the y axis reading 0.00000005, 0.00000007, 0.00000009, it reads 0.5,0.7,0.9 and then says 1e-7 at the top of the axis). However some of my plots don't scale the axes automatically, and I would like to get advise of how to do that manually.
I have found threads on manually setting the tick marks, however I haven't been able to find threads on scaling only.
I can't imbed pictures but here is a link to a picture of what I would like to do: Ideal y axis and here's link to a picture of what I want to avoid: Current y axis.
I'm using seaborn formatting and matplotlib for plots and my code looks like this:
plt.plot(x_j_n,y_j_n, label='Scanning i negativ retning', color='grey', ls='dashed')
plt.plot(x_j_p,y_j_p, label='Scanning i positiv retning', color='black', ls='dashed')
plt.errorbar(x_j_n,y_j_n, yerr=std_j_n, fmt='o', color='black', mfc='white', label = 'Usikkerhed')
plt.errorbar(x_j_p,y_j_p, yerr=std_j_p, fmt='o', color='grey', mfc='white', label = 'Usikkerhed')
plt.ylabel('Målt spænding i volt (V)')
plt.xlabel('Påtrykt felt i tesla (T)')
plt.legend()
plt.show;
Set the y axis to scientific:
plt.gca().yaxis.get_major_formatter().set_scientific(True)
For example:
x = [1100000,2200000,3300000]
y = [1100000,2200000,3300000]
plt.plot(x,y)
plt.gca().xaxis.get_major_formatter().set_scientific(False)
plt.gca().yaxis.get_major_formatter().set_scientific(True)
plt.show()
will give:

Plot multiple graphs in matplotlib, setting labels and size of each graph

I want to plot multiple graphs in a matrix (4,2) and I want that the figures at the left side have their labels in their left side and the opposite for the right side. Additionally, when I plot them in Google Colab, the graphs are all squished together, so I would like to increase their size and the spacing between them. And in the end, I would like that only the two graphs at the bottom have the x label.
Could anyone give me some tips on what functions or internal parameters to use? Additionally, there is some function where I can see my graphs in another window of my browser, instead of bellow my code box of Colab or something like this?
I would also be happy if you could give me tips to avoid unnecessary code.
This is my code, so far:
x = df_clean['SIO2']
fig, axs = plt.subplots(4, 2)
axs[0,0].plot(x, df_clean['AL2O3'], 'bo', markersize=1)
axs[0,1].plot(x, df_clean['MGO'], 'bo', markersize=1)
axs[1,0].plot(x, df_clean['FEOT'], 'bo', markersize=1)
axs[1,1].plot(x, df_clean['CAO'], 'bo', markersize=1)
axs[2,0].plot(x, df_clean['NA2O'], 'bo', markersize=1)
axs[2,1].plot(x, df_clean['K2O'], 'bo', markersize=1)
axs[3,0].plot(x, df_clean['TIO2'], 'bo', markersize=1)
axs[3,1].plot(x, df_clean['P2O5'], 'bo', markersize=1)
plt.suptitle('Harker Diagrams (All data)')
plt.figure(figsize=(60, 45))
And this is what I'm getting back:
If you want to determine specific position, orientation, size, color, etc. of axis labels use ax.annotate(). You can read the docs here about how to use it. There are way too many options to mention them all here but play around with it and you can get precise labels.
As for adjusting the spacing between the plots, use the wspace and hspace options of fig.subplots_adjust(), which you can read about here.
If you want the x axis label to appear only on the bottom you should use sharex=True when you initially call plt.subplots(). Also a good idea to set sharey=True if all your plots have the same y axis.
You can adjust the size of the overall diagram (which in turn will adjust the size of each individual plot) by setting figsize=(width, height) when you call plt.subplots().
Not sure about getting the output to come up in a different browser window, but these functions should help you make a cleaner looking graph.

Python implementation of non uniform (non linear) x-axis in matplotlib

I am trying to have a non linear x - axis in Python using matplotlib and haven't found any functions or hack arounds to this problem.
This is how our graph looks at this point of time and I want to convert it to something like this. (Look at the difference in x axes of both graphs)
The code I have as of now is:
plt.axis([0, 100, 0, 1])
plt.plot(onecsma_x, onecsma_y, label='1-CSMA')
plt.plot(slotted_aloha_x,slotted_aloha_y, label ='Slotted Aloha')
plt.plot(pure_aloha_x,pure_aloha_y, label ='Pure Aloha')
plt.plot(npcsma_x, npcsma_y, label ='Non persisten CSMA')
plt.plot(pcsma_x, pcsma_y, label ='P persistent CSMA')
plt.legend(loc='upper right')
plt.show()
For log x-axis use semilogx instead of plot.
Also you could limit the x-axis maybe after using semilogx (but before show) with:
plt.xlim(0, 10**2)

Missing plots after for loop

I have a dataset that I want to plot, and also do a linear regression on the data in some invervals, plotting it in the same graph.
But I have some problems with this... The main graph is plotted first, the intervals and the linear regression in the for loop:
plt.plot(Trec, lnp, 'r-')
for i in range(len(Werte)):
plt.plot( subset(Time, Trec, Data[i][5], Data[i][6])[1], subset(Time, Trec, Data[i][5], Data[i][6])[1] * Data[i][2] + Data[i][4])
plt.axvline(x=Data[i][5])
plt.show()
With this code it only plots me the last iteration of the for loop. By itself, the commands all do what I intend them to do... What am I doing wrong?
What you want is superimposing figures on the same plot. For that purpose, you can use the axis object returned by subplots.
fig, ax = plt.subplots()
ax.plot(...) # plot your data here
ax.plot(...) # plot your interval and regression here.
plt.show()

Categories

Resources