Sometimes, I need to save my figure with plt.savefig("./xxx.pdf") or plt.savefig("./xxx.png"). Other than pngfile contain all the information of the plots, the xlabel and ylabel disappear in the .pdffile.
Here is an example. The plot code code are presented here.
import mpl_toolkits.mplot3d.axes3d as axes3d
fig,ax = plt.subplots(subplot_kw=dict(projection='3d'),figsize = (10,6))
lon_grid = np.linspace(x_map1,x_map2,len(x_grid))
lat_grid = np.linspace(y_map1,y_map2,len(y_grid))
xx,yy = np.meshgrid(lon_grid,lat_grid)
ax.plot_surface(xx, yy,so2_mean,rstride = 1,cstride = 1,\
cmap=plt.cm.Spectral_r,linewidth = 0)
ax.set_xticklabels(["114.2","114.4","114.6","114.8"])
plt.yticks(np.arange(37.7, 38.4, 0.2))
ax.set_yticklabels(["114.2","114.4","114.6","114.8"])
ax.set_zlabel(u'FOM'+ r'$\mathregular{(\mu g/m^3)}$',rotation = 90,fontsize = 14)
ax.set_xlabel(u'lon',fontsize = 14),ax.set_ylabel(u'lat',fontsize = 14)
ax.view_init(azim=-55,elev =35)
plt.autoscale(False)
ax.scatter(site_s.LON,site_s.LAT,site_s.CONC+2,marker= '^',color = "k",s = 50)
plt.tight_layout()
plt.savefig("./Fig/Fig.pdf")
plt.savefig("./Fig/Fig.png")
plt.show()
The Fig.pdf shows like this:
The Fig.png shows like this:
The xlabel and ylabel are missing in pdf file
Related
I want Python 3 to wait till the plot was displayed before the print statement is executed. Right now it looks like that:
This is the relevant part of my code:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(filename)
headers = list(df)
attribute = str(input("Which attribute would you like to analyze?\n"))
attribute_mean = df[attribute].mean()
attribute_std = df[attribute].std()
ax = df.plot.bar(x=headers[0], y=str(attribute), label=("_"+attribute))
ax.axhline(attribute_mean, color="red", label="mean")
ax.axhline((float(attribute_mean) + float(attribute_std)), color="green", label="std")
ax.axhline((float(attribute_mean) - float(attribute_std)), color="green", )
ax.legend(["mean", "+std", "-std"])
plt.ylabel(attribute)
plt.xlabel(headers[0])
plt.margins(x=0, y=0)
fig = plt.gcf()
leg = plt.legend(loc = 'upper right')
fig.show()
print("The presented data showed the following characteristic values:\n")
display(df[attribute].describe())
Is there a way to fix this?
I have the following code and graph and am wondering how I could add some text to it. On each bar I would like the min (where it begins) and the max (where it ends) displayed just inside the boxes and I would also like to place the average of each data set where it falls inside the box. The code is what I already have and the link goes to an example of what the final product should look similar too.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
preRawData = [60,55,67,68,70,71]
postRawData = [71,75,80,77,73,74]
dataDict = {}
delta = 0.4
minPre = min(preRawData)
minPost = min(postRawData)
maxPre = max(preRawData)
maxPost = max(postRawData)
preAverage = sum(preRawData)/len(preRawData)
postAverage = sum(postRawData)/len(postRawData)
preRange = (minPre, maxPre)
postRange = (minPost, maxPost)
dataDict.update({'Pre' : preRange})
dataDict.update({'Post' : postRange})
yspan = len(dataDict)
yplaces = [.5+i for i in range(yspan)]
ylabels = sorted(dataDict.keys())
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_yticks(yplaces)
ax.set_yticklabels(ylabels)
ax.set_ylim((0,yspan))
preStart, preEnd = dataDict['Pre']
postStart, postEnd = dataDict['Post']
low, hi = dataDict[ylabels[0]]
ax.add_patch(patches.Rectangle((postStart,yplaces[0]-
delta/2.0),postEnd-postStart,delta, edgecolor='black',
facecolor='red'))
if postStart<low : low=postStart
if postEnd>hi : hi=postEnd
ax.add_patch(patches.Rectangle((preStart,yplaces[1]-
delta/2.0),preEnd-preStart,delta, edgecolor='black',
facecolor='green'))
if preStart<low : low=preStart
if preEnd>hi : hi=preEnd
ax.plot((low,hi),(0,0))
xmin, xmax = ax.get_xlim()
ax.hlines(range(1, yspan),xmin,xmax)
ax.grid(axis='x')
plt.show()
https://imgur.com/a/uBSVydh
I am using a github repository called ptitprince, which is derived from seaborn and matplotlib, to generate graphs.
For example, this is the code using the ptitprince repo:
# coding: utf8
import pandas as pd
import ptitprince as pt
import seaborn as sns
import os
import matplotlib.pyplot as plt
#sns.set(style="darkgrid")
#sns.set(style="whitegrid")
#sns.set_style("white")
sns.set(style="whitegrid",font_scale=2)
import matplotlib.collections as clt
df = pd.read_csv ("u118phag.csv", sep= ",")
df.head()
savefigs = True
figs_dir = 'figs'
if savefigs:
# Make the figures folder if it doesn't yet exist
if not os.path.isdir('figs'):
os.makedirs('figs')
#automation
f, ax = plt.subplots(figsize=(4, 5))
#f.subplots_adjust(hspace=0,wspace=0)
dx = "Treatment"; dy = "score"; ort = "v"; pal = "Set2"; sigma = .2
ax=pt.RainCloud(x = dx, y = dy, data = df, palette = pal, bw = sigma,
width_viol = .6, ax = ax, move=.2, offset=.1, orient = ort, pointplot = True)
f.show()
if savefigs:
f.savefig('figs/figure20.png', bbox_inches='tight', dpi=500)
which generates the following graph
The raw code not using ptitprince is as follows and produces the same graph as above:
# coding: utf8
import pandas as pd
import ptitprince as pt
import seaborn as sns
import os
import matplotlib.pyplot as plt
#sns.set(style="darkgrid")
#sns.set(style="whitegrid")
#sns.set_style("white")
sns.set(style="whitegrid",font_scale=2)
import matplotlib.collections as clt
df = pd.read_csv ("u118phag.csv", sep= ",")
df.head()
savefigs = True
figs_dir = 'figs'
if savefigs:
# Make the figures folder if it doesn't yet exist
if not os.path.isdir('figs'):
os.makedirs('figs')
f, ax = plt.subplots(figsize=(7, 5))
dy="Treatment"; dx="score"; ort="h"; pal = sns.color_palette(n_colors=1)
#adding color
pal = "Set2"
f, ax = plt.subplots(figsize=(7, 5))
ax=pt.half_violinplot( x = dx, y = dy, data = df, palette = pal, bw = .2, cut = 0.,
scale = "area", width = .6, inner = None, orient = ort)
ax=sns.stripplot( x = dx, y = dy, data = df, palette = pal, edgecolor = "white",
size = 3, jitter = 1, zorder = 0, orient = ort)
ax=sns.boxplot( x = dx, y = dy, data = df, color = "black", width = .15, zorder = 10,\
showcaps = True, boxprops = {'facecolor':'none', "zorder":10},\
showfliers=True, whiskerprops = {'linewidth':2, "zorder":10},\
saturation = 1, orient = ort)
if savefigs:
f.savefig('figs/figure21.png', bbox_inches='tight', dpi=500)
Now, what I'm trying to do is to figure out how to modify the graph so that I can (1) move the plots closer together, so there is not so much white space between them, and (2) shift the x-axis to the right, so that I can make the distribution (violin) plot wider without it getting cut in half by the y-axis.
I have tried to play around with subplots_adjust() as you can see in the first box of code, but I receive an error. I cannot figure out how to appropriately use this function, or even if that will actually bring the different graphs closer together.
I also know that I can increase the distribution size by increasing this value width = .6, but if I increase it too high, the distribution plot begins to being cut off by the y-axis. I can't figure out if I need to adjust the overall plot using the plt.subplots,or if I need to move each individual plot.
Any advice or recommendations on how to change the visuals of the graph? I've been staring at this for awhile, and I can't figure out how to make seaborn/matplotlib play nicely with ptitprince.
You may try to change the interval of X-axis being shown using ax.set_xbound (put a lower value than you currently have for the beginning).
I want to draw multiple ternary graphs and thought to do this using matplotlib's subplot.
I'm just getting empty 'regular' plots though, not the ternary graphs I want in there. I found the usage of
figure, ax = plt.subplots()
tax = ternary.TernaryAxesSubplot(ax=ax)
so this seems to be possible, but can't really find out how to get this working. Any ideas?
Code I'm using:
I'm using a for loop as the data has columns named tria1-a, tria2-a, etc for the different triads
import ternary
import matplotlib.pyplot as plt
import pandas as pd
#configure file to import.
filename = 'somecsv.csv'
filelocation = 'location'
dfTriad = pd.read_csv(filelocation+filename)
# plot the data
scale = 33
figure, ax = plt.subplots()
tax = ternary.TernaryAxesSubplot(ax=ax, scale=scale)
figure.set_size_inches(10, 10)
tax.set_title("Scatter Plot", fontsize=20)
tax.boundary(linewidth=2.0)
tax.gridlines(multiple=1, color="blue")
tax.legend()
tax.ticks(axis='lbr', linewidth=1, multiple=5)
tax.clear_matplotlib_ticks()
#extract the xyz columns for the triads from the full dataset
for i in range(1,6) :
key_x = 'tria'+ str(i) + '-a'
key_y = 'tria' + str(i) + '-b'
key_z = 'tria' + str(i) + '-c'
#construct dataframe from the extracted xyz columns
dfTriad_data = pd.DataFrame(dfTriad[key_x], columns=['X'])
dfTriad_data['Y'] = dfTriad[key_y]
dfTriad_data['Z'] = dfTriad[key_z]
#create list of tuples from the constructed dataframe
triad_data = [tuple(x) for x in dfTriad_data.to_records(index=False)]
plt.subplot(2, 3, i)
tax.scatter(triad_data, marker='D', color='green', label="")
tax.show()
I had the same problem and could solve it by first "going" into the subplot, then creating the ternary figure in there by giving plt.gca() as keyword argument ax:
plt.subplot(2,2,4, frameon = False)
scale = 10
plt.gca().get_xaxis().set_visible(False)
plt.gca().get_yaxis().set_visible(False)
figure, tax = ternary.figure(ax = plt.gca(), scale = scale)
#now you can use ternary normally:
tax.line(scale * np.array((0.5,0.5,0.0)), scale*np.array((0.0, 0.5, 0.5)))
tax.boundary(linewidth=1.0)
#...
I have the code below, in the x-axis, i want to show only the parameter values for which i have the metric values which are 5,10,20 and 50.
I want the parameter values to span the x-axis.
How I can do it ?.
import matplotlib.pyplot as plt;
import numpy as np;
from matplotlib import rc;
fig, ax1 = plt.subplots();
rc('mathtext', default='regular');
x = np.array([5,10,20,50]);
cg1 = np.array([0.1,0.3,0.5,0.8]);
cg2 = np.array([0.2,0.2,0.4,0.7]);
cg3 = np.array([0.3,0.4,0.6,0.6]);
lns1 = ax1.plot(x,cg1,'b*:',label='1 CG');
lns2 = ax1.plot(x,cg2,'bo--',label='2 CG');
lns3 = ax1.plot(x,cg3,'bs-',label='3 CG');
ax1.set_ylabel('CG',color='b');
ax1.set_ylim([0,1]);
ax1.set_xlim([4,55]);
ax1.set_xticklabels([5,10,20,50]);
ax1.set_xlabel('K');
ax2 = ax1.twinx();
ld1 = np.array([0.8,0.5,0.2,0.2]);
ld2 = np.array([0.6,0.2,0.3,0.2]);
ld3 = np.array([0.2,0.4,0.6,0.2]);
lns4 = ax2.plot(x,ld1,'k*:',label='1 ld');
lns5 = ax2.plot(x,ld2,'ko--',label='2 ld');
lns6 = ax2.plot(x,ld3,'ks-',label='3 ld');
lns = lns1 + lns2 + lns3 + lns4 + lns5 + lns6;
labs = [l.get_label() for l in lns];
ax1.legend(lns, labs, loc='best', ncol=2);
ax2.set_ylabel('LD',color='k');
ax2.set_ylim([0,1]);
ax2.set_xlim([4,55]);
plt.show();
Try replacing line with ax1.set_xlim([4,55]) with this line:
ax1.set_xticks(x)
You may also want to remove ax2.set_xlim(...).
Does it give you what you expected?
UPDATE Following comments:
Please use these lines (NOTE: the order matters!):
ax1.set_xlim([4,55]);
ax1.set_xticks(x)
...
ax2.set_xlim([4,55]);
ax2.set_xticks(x)
And remove anything else that touches xticks, like any of these:
ax1.set_xticklabels([5,10,20,50]);
ax2.set_xticklabels([5,10,20,50]);
This should produce a chart like this:
Which has limits at [4, 55] and only selected tick values visible.