Too many subplots for pyplot? - python

I am working on a program that plots a decent amount of graphs (the current iteration is outputting 250-300 graphs). I am using subplots so as to condense them to one output/window. However, the output is extremely condensed.
I was hoping that the output would maintain the dimensions of a "regular" plot and output a scroll-able window, as opposed to maintaining the dimensions of the output window and scaling the subplots down. Is there a way to fix this, besides outputting every n plots?
Here is the code that outputs the plots:
f, axarr = plt.subplots(len(events)-1, sharex = True)
x_axis = np.arange(120)
for i in range(len(events)-1):
axarr[i].plot(x_axis,events[i])
plt.show()

Related

Make two plots in a single row using imshow in python

I want to make plots of the same data for two regions, so they should be placed side by side in a single row for compactness.
Below is my code. As we can expect, it's creating the plots one after another in a column, since the two plots are not linked to each other.
I tried looking for side by side plot methods, however they don't seem to work with imshow() and I need to use imshow() in my code. I've attached my output below as well.
Any suggestions?
wvcount3D=fanibl['IMG_WV'][:]
wvcount3D.shape
wvcount=np.squeeze(wvcount3D)
wvcount.shape
image_wv_global=plt.imshow(wvcount,vmin=800,vmax=975)
plt.title("Global 2D plot for Water Vapor Count for Fani before landfall")
plt.colorbar(image_wv_global)
plt.grid()
plt.show()
image_wv_asia=plt.imshow(wvcount,vmin=800,vmax=975)
plt.title("Asia-specific plot for Water Vapor Count for Fani before landfall")
plt.axis([300, 1000, 200, 700])
plt.colorbar(image_wv_asia)
plt.grid()
plt.show()
This is my current output, plots in a single column:

Resizing the figure in python and then editing x ticks does not work

I have a pandas dataframe and I am trying to plot a line. The plotting is fine but I have issues with the x-ticks labels because I want to supply my own, and I want to modify the figure size so its width can take all the ticks without overlapping issues (rotation is not enough). The problem I am facing is that when I resize the figure, it creates a new empty figure (with no plots) rather than modifying the one with the plots. It does adds the x-ticks correctly but in a separate figure. How to solve this issue? Below is my code:
dataset = read_csv('bbm.csv', header=0) #index_col=0)
#dataset=dataset.head(20)
raw_values = dataset.values
#dataset.columns
print(dataset.head())
ax=dataset.plot(x="Date", y=["US","Papers"]);
x=dataset['Date']
m=dataset['Month']
num_elements = len(x)
X_Tick_List = []
X_Tick_Label_List=[]
for item in range (0,num_elements):
X_Tick_List.append(item)
X_Tick_Label_List.append(m[item])
pyplot.figure(figsize=(20,5))
pyplot.xticks(ticks=X_Tick_List,labels=X_Tick_Label_List, rotation=0,fontsize=8)
pyplot.show()

Is it possible to automatically scale the figure size, but keep the plot size constant in matplotlib?

I am using matplotlib to create multiple bar plots using the following code:
fig = plt.figure(figsize=(4, 4))
plt.barh(y=y, width=width, height=0.5)
plt.yticks(y, labels)
plt.xlabel("Contribution")
plt.tight_layout()
plt.show()
Since the length of my y-ticks labels can vary, the plot can get squeezed together as in the case below:
In other cases the plot looks fine:
Now, I was wondering, if there is an option in matplotlib to keep the plot size constant, but scale the figure size automatically (in horizontal direction)? My goal is that the plot size stays always the same, independent of the y-label length (because they vary inbetween plots). Thank you!

Peculiar horizontal lines in 3d plots

I am trying to make a 3d plot as using 3 2d arrays. I get the plot just fine but I want to truncate the axes using ax.set_xlim()
This is the original plot I have:
I want to remove the long tails for each curve. I use ax.set_xlim(0,30) and this is the result:
I want to get rid of the extra part that is flowing out of the graph area. If I reduce the limits futher with ax.set_xlim(0,25), I get something even more weird:
Ideally, I would want the x-axis to only show points until 25. How can I get rid of the extra parts?
Thanks in advance!
The code (the arrays are being read from a file):
fig = plt.figure()
ax = plt.axes(projection = '3d')
for i in range(5):
ax.plot(E[:,i], freq[:,i], DF[:,i])
ax.set_zlabel(filename + "$\ [eV^{-1} cm^{-3}]$")
ax.set_xlabel("$\epsilon [eV]$")
ax.set_ylabel("f [MHz]")
ax.set_xlim(0,25)
ax.set_yticks(freq[0])
fig.savefig(filename+"3d.png", dpi = 1500, bbox_inches='tight')
Data file from where the data is being read: File

Adding error bars to Matplotlib-generated graph of Pandas dataframe creates invalid legend

I am trying to graph a Pandas dataframe using Matplotlib. The dataframe contains four data columns composed of natural numbers, and an index of integers. I would like to produce a single plot with line graphs for each of the four columns, as well as error bars for each point. In addition, I would like to produce a legend providing labels for each of the four graphed lines.
Graphing the lines and legend without error bars works fine. When I introduce error bars, however, the legend becomes invalid -- the colours it uses no longer correspond to the appropriate lines. If you compare a graph with error bars and a graph without, the legend and the shapes/positions of the curves remain exactly the same. The colours of the curves get switched about, however, so that though the same four colours are used, they now correspond to different curves, meaning that the legend now assigns the wrong label to each curve.
My graphing code is thus:
def plot_normalized(agged, show_errorbars, filename):
combined = {}
# "agged" is a dictionary containing Pandas dataframes. Each dataframe
# contains both a CPS_norm_mean and CPS_norm_std column. By running the code
# below, the single dataframe "combined" is created, which has integer
# indices and a column for each of the four CPS_norm_mean columns contained
# in agged's four dataframes.
for k in agged:
combined[k] = agged[k]['CPS_norm_mean']
combined = pandas.DataFrame(combined)
plt.figure()
combined.plot()
if show_errorbars:
for k in agged:
plt.errorbar(
x=agged[k].index,
y=agged[k]['CPS_norm_mean'],
yerr=agged[k]['CPS_norm_std']
)
plt.xlabel('Time')
plt.ylabel('CPS/Absorbency')
plt.title('CPS/Absorbency vs. Time')
plt.savefig(filename)
The full 100-line script is available on GitHub. To run, download both graph.py and lux.csv, then run "python2 graph.py". It will generate two PNG files in your working directory -- one graph with error bars and one without.
The graphs are thus:
Correct graph (with no error bars):
Incorrect graph (with error bars):
Observe that the graph without error bars is properly labelled; note that the graph with error bars is improperly labelled, as though the legend is identical, the line graphs' changed colours mean that each legend entry now refers to a different (wrong) curve.
Thanks for any help you can provide. I've spent a number of extremely aggravating hours bashing my head against the wall, and I suspect that I'm making a stupid beginner's mistake. For what it's worth, I've tried with the Matplotlib development tree, version 1.2.0, and 1.1.0, and all three have exhibited identical behaviour.
I am new to programming and python in general but I managed to throw together a dirty fix, the legends are now correct, the colors are not.
def plot_normalized(agged, show_errorbars, filename):
combined = {}
for k in agged:
combined[k] = agged[k]['CPS_norm_mean']
combined = pandas.DataFrame(combined)
ax=combined.plot()
if show_errorbars:
for k in agged:
plt.errorbar(
x=agged[k].index,
y=agged[k]['CPS_norm_mean'],
yerr=agged[k]['CPS_norm_std'],
label = k #added
)
if show_errorbars: #try this, dirty fix
labels, handles = ax.get_legend_handles_labels()
N = len(handles)/2
plt.legend(labels[:N], handles[N:])
#Why does the fix work?:
#labels, handles = ax.get_legend_handles_labels()
#print handles
#out:
#[u'Blank', u'H9A', u'Q180K', u'Wildtype', 'Q180K', 'H9A', 'Wildtype', 'Blank']
#Right half has correct order, these are the labels from label=k above in errorplot
plt.xlabel('Time')
plt.ylabel('CPS/Absorbency')
plt.title('CPS/Absorbency vs. Time')
plt.savefig(filename)
Produces:

Categories

Resources