I am learning matplotlib.
I am trying to plot two below plots in a single plot using matplotlib.
But it overlaps.
Here is my code.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
train_error = [0.26462888486225206, 0.26462383329393313, 0.2628674962680674, 0.2553700231555298, 0.17473717177688022, 0.14773444580059242, 0.1468299949185866, 0.1468235689407127, 0.1439370366766204]
test_error = [0.8438224756653776, 0.8442034650577578, 1.018608707726192, 4.853704454584892, 123.69312582226338, 798.4569874115062, 3205.5264038946007, 9972.587330411312, 10787335.618580218]
plt.plot(train_error)
plt.plot(test_error)
plt.show()
Where am i doing wrong ? Can anyone please guide / help ?
Use the subplot
Go check https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html
plt.subplot(1,2,1)
plt.plot(train_error)
plt.subplot(1,2,2)
plt.plot(test_error)
in plt.subplot(a,b,x) you have a,b that represents the number of (row and column) you want vertically and horizontally and x the index of the subplot selected counting from left to right and top to bottom.
Related
I'm experimenting with seaborn and have a question about specifying axes properties. In my code below, I've taken two approaches to creating a heatmap of a matrix and placing the results on two sets of axes in a figure.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
A=np.random.randn(4,4)
labels=['a','b','c','d']
fig, ax = plt.subplots(2)
sns.heatmap(ax =ax[0], data = A)
ax[0].set_xticks(range(len(labels)))
ax[0].set_xticklabels(labels,fontsize=10,rotation=45)
ax[0].set_yticks(range(len(labels)))
ax[0].set_yticklabels(labels,fontsize=10,rotation=45)
ax[1].set_xticks(range(len(labels)))
ax[1].set_xticklabels(labels,fontsize=10,rotation=45)
ax[1].set_yticks(range(len(labels)))
ax[1].set_yticklabels(labels,fontsize=10,rotation=45)
sns.heatmap(ax =ax[1], data = A,xticklabels=labels, yticklabels=labels)
plt.show()
The resulting figure looks like this:
Normally, I would always take the first approach of creating the heatmap and then specifying axis properties. However, when creating an animation (to be embedded on a tkinter canvas), which is what I'm ultimately interested in doing, I found such an ordering in my update function leads to "flickering" of axis labels. The second approach will eliminate this effect, and it also centers the tickmarks within squares along the axes.
However, the second approach does not rotate the y-axis tickmark labels as desired. Is there a simple fix to this?
I'm not sure this is what you're looking for. It looks like you create your figure after you change the yticklabels. so the figure is overwriting your yticklabels.
Below would fix your issue.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
A=np.random.randn(4,4)
labels=['a','b','c','d']
fig, ax = plt.subplots(2)
sns.heatmap(ax =ax[0], data = A)
ax[0].set_xticks(range(len(labels)))
ax[0].set_xticklabels(labels,fontsize=10,rotation=45)
ax[0].set_yticks(range(len(labels)))
ax[0].set_yticklabels(labels,fontsize=10,rotation=45)
ax[1].set_xticks(range(len(labels)))
ax[1].set_xticklabels(labels,fontsize=10,rotation=45)
ax[1].set_yticks(range(len(labels)))
sns.heatmap(ax =ax[1], data = A,xticklabels=labels, yticklabels=labels)
ax[1].set_yticklabels(labels,fontsize=10,rotation=45)
plt.show()
I need help creating a dot plot in Python like the one from the image.
The exercise consists on graphing the following data 74.001 , 74.003, 74.015, 74.000, 74.005, 74.004. I'm having some trouble with doing the dot plot because I can't find how to do it.
Here you go:
import matplotlib.pyplot as plt
y =[74.001 , 74.003, 74.015, 74.000, 74.005, 74.004]
fig = plt.plot(y,'o', fillstyle='none')
Next time you post a question, include a MRE (Minimum Reproducible Example) showing what you have done.
Using plotly and also defining x which was not provided.
import plotly.express as px
y =[74.001 , 74.003, 74.015, 74.000, 74.005, 74.004]
x =[12.4,12.5,12.5,12.6,12.7, 12.8]
px.scatter(x=x, y=y).update_traces(marker_symbol="circle-open", marker_line_width=3)
My goal is to create a barplot visualized with sequential colors.
The only problem I face right now is that the color distribution repeats after a few bars (see pic).
I want the color-distribution to span the whole x-range.
Any ideas how to do this?
pretty easy if you're using matplotlib & seaborn:
import matplotlib.pyplot as plt
import seaborn as sns
x = range(10)
y = range(10)
plt.bar(x,y,color= sns.color_palette("BuGn_r", len(x)))
plt.show()
just pass the length of the x-array as the 2nd parameter of color_palette()
Normally if you plot two different figures using the default settings in pyplot, they will be exactly the same size, and if saved can be neatly aligned in PowerPoint or the like. I'd like to generate one figure, however, which has a legend outside of the figure. The script I'm using is shown below.
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)
fig1=plt.figure(1)
plt.plot(x,y1,label='y1')
handles1,labels1=plt.gca().get_legend_handles_labels()
lgd1=plt.gca().legend(handles1,labels1,bbox_to_anchor=(1.27,1),borderaxespad=0.)
fig2=plt.figure(2)
plt.plot(x,y2)
fig1.savefig('fig1',bbox_extra_artists=(lgd1,),bbox_inches='tight')
fig2.savefig('fig2')
plt.show()
The problem is that in PowerPoint, I can no longer align the two figures left and have their axes aligned. Due to the use of the 'extra artists' and 'bbox_inches=tight' arguments for the first figure, the width of its margins becomes different from the second figure.
Is there any way to 'transfer' the clip box from the first figure to the second figure, such that they can be aligned by 'align left' in PowerPoint?
I think an easier way to achieve what you want is to just construct one figure with two subplots, and let matplotlib align everything for you.
Do you think doing something like this is a good idea?
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)
fig = plt.figure()
a = fig.add_subplot(211)
a.plot(x,y1, label='y1')
lgd1 = a.legend(bbox_to_anchor = (1.27,1), borderaxespad=0.)
a = fig.add_subplot(212)
a.plot(x,y2)
fig.savefig('fig',bbox_extra_artists=(lgd1,),bbox_inches='tight')
I'm trying to compose an image with both 2D and 3D plot. so far I've done the following:
import idlsave
import matplotlib
from matplotlib import *
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
fig = plt.figure(figsize=(18,5))
ax = fig.add_subplot(1,3,1, projection='3d',azim=-133,elev=14)
l = ax.plot3D(X3D,Y3D,Z3D,lw=2,color='red')
ax.set_xlim3d(-10,10)
ax.set_ylim3d(-10,10)
ax.set_zlim3d(-10,10)
ax.text(-2,-7,-11,'b$_r$ [mT]','x')
ax.text(-5,-1,-11,'b$_p$ [mT]','y')
ax.set_zlabel(r'b$_t$ [mT]')
ax.plot([bEq[0],-bEq[0]],[bEq[1],-bEq[1]],[bEq[2],-bEq[2]],'b--',lw=2)
ax.plot([pLe[0],-pLe[0]],[pLe[1],-pLe[1]],[pLe[2],-pLe[2]],color='black',lw=2)
ax.text(3,12,9.2,'(a)', fontsize=14)
ax = fig.add_subplot(1,3,2)
l = ax.plot(br,bp,'k-',lw=2)
ax.set_xlabel(r'b$_{\lambda_1}$ [mT]')
ax.set_ylabel(r'b$_{\lambda_2}$ [mT]')
ax.set_xlim(-2,6.3)
ax.set_ylim(-5.5,5.5)
ax.plot([0,0],[-5.5,5.5],'k-.')
ax.plot([-2,6.3],[0,0],'k-.')
e=Ellipse((pf[2],pf[3]),2*pf[0],2*pf[1],- pf[4]*57.2958,fc='none',lw=2,ls='dashed',ec='red')
ax.add_artist(e)
ax.text(-1,4, '(b)', fontsize=14)
ax = fig.add_subplot(1,3,3)
ax.plot(-bxDip,-byDip,'b-',lw=2,label='$\mathcal{D}$')
ax.plot(-bxMon,-byMon,'r-',lw=2,label='$\mathcal{M}$')
ax.set_xlabel(r'b$_{\lambda_1}$')
ax.set_ylabel(r'b$_{\lambda_2}$')
ax.set_xlim(-4,12)
ax.set_ylim(-6,7)
ax.plot([-4,12],[0,0],'k-.')
ax.plot([0,0],[-6,7],'k-.')
ax.legend(loc='upper right')
ax.text(-3,5.5, '(c)', fontsize=14)
plt.savefig("../pdf_box/fig3.pdf",bbox_inches='tight')
Wit the present code I was able to produce the figure reported here http://img219.imageshack.us/i/fig3e.png/
There are two question which puzzle me.
1) As you can see the 3D plot is smaller than the other two and there is enough white spaces between the subplots to increase the size. How can I do this? i.e. How can I enlarge the size of one subplot, eventually decreasing the other two?
2) I would like to exclude the grey background in the 3D plot.
Any help is very welcomed.
Change ax.dist for the 3D plot. This will cause the rendered graphic to fill more of the subplot area. Here is a similar question. You may find some more info there.
You may also want to adjust the widths of the subplots with respect to each other (increase the width of the 3d plot and shrink the 2D plots. This can be accomplished with subplots_adjust