How to plot and save with an <AxesSubplot:> output - python

I am using this function
It return one AxesSubplot:
I would like to save the plot that is ploted when show_plot=True as a png without changing the function.
How should I proceed ?
Best regards !

To get the whole figure, you could try:
ax.get_figure().savefig('fig_name.png')
If you have a figure with multiple subplots and you want to only extract one (ax):
# Get the bounding box of the subplot and expand it to include the axis labels and ticks.
# You will have to play with the expanded parameters.
subplot_box = ax.get_window_extent().transformed(ax.get_figure().dpi_scale_trans.inverted()).expanded(1.2, 1.4)
ax.get_figure().savefig('subplot.png', bbox_inches=extent)

Related

How to remove labeling and tickering in WFDB, python?

enter image description here
The plots have label and tick information and I'd like to remove them.
I downloaded ECG data from Pysionet(https://physionet.org/content/?topic=ecg) and try to analze the images.
Since I just need the signal images, want to remove any other parts including labels and ticks.
However, there are no parameters related to it and doesn't work with any plt options.
How could I get just the sinal images?
You can get access to the matplotlib figure generated by wfdb_plot via return_fig=True. This way, you can disable any axis annotations and titles:
fig = wfdb.plot_wfdb(record=rcbr, figsize=(10,4), return_fig=True)
fig.axes.axis("off") # disable ticks, labels, etc.
fig.axes.set_title("") # remove title

Why am I unable to make a plot containing subplots in plotly using a px.scatter plot?

I have been trying to make a figure using plotly that combines multiple figures together. In order to do this, I have been trying to use the make_subplots function, but I have found it very difficult to have the plots added in such a way that they are properly formatted. I can currently make singular plots (as seen directly below):
However, whenever I try to combine these singular plots using make_subplots, I end up with this:
This figure has the subplots set up completely wrong, since I need each of the four subplots to contain data pertaining to the four methods (A, B, C, and D). In other words, I would like to have four subplots that look like my singular plot example above.
I have set up the code in the following way:
for sequence in sequences:
#process for making sequence profile is done here
sequence_df = pd.DataFrame(sequence_profile)
row_number=1
grand_figure = make_subplots(rows=4, cols=1)
#there are four groups per sequence, so the grand figure should have four subplots in total
for group in sequence_df["group"].unique():
figure_df_group = sequence_df[(sequence_df["group"]==group)]
figure_df_group.sort_values("sample", ascending=True, inplace=True)
figure = px.line(figure_df_group, x = figure_df_group["sample"], y = figure_df_group["intensity"], color= figure_df_group["method"])
figure.update_xaxes(title= "sample")
figure.update_traces(mode='markers+lines')
#note: the next line fails, since data must be extracted from the figure, hence why it is commented out
#grand_figure.append_trace(figure, row = row_number, col=1)
figure.update_layout(title_text="{} Profile Plot".format(sequence))
grand_figure.append_trace(figure.data[0], row = row_number, col=1)
row_number+=1
figure.write_image(os.path.join(output_directory+"{}_profile_plot_subplots_in_{}.jpg".format(sequence, group)))
grand_figure.write_image(os.path.join(output_directory+"grand_figure_{}_profile_plot_subplots.jpg".format(sequence)))
I have tried following directions (like for example, here: ValueError: Invalid element(s) received for the 'data' property) but I was unable to get my figures added as is as subplots. At first it seemed like I needed to use the graph object (go) module in plotly (https://plotly.com/python/subplots/), but I would really like to keep the formatting/design of my current singular plot. I just want the plots to be conglomerated in groups of four. However, when I try to add the subplots like I currently do, I need to use the data property of the figure, which causes the design of my scatter plot to be completely messed up. Any help for how I can ameliorate this problem would be great.
Ok, so I found a solution here. Rather than using the make_subplots function, I just instead exported all the figures onto an .html file (Plotly saving multiple plots into a single html) and then converted it into an image (HTML to IMAGE using Python). This isn't exactly the approach I would have preferred to have, but it does work.
UPDATE
I have found that plotly express offers another solution, as the px.line object has the parameter of facet that allows one to set up multiple subplots within their plot. My code is set up like this, and is different from the code above in that the dataframe does not need to be iterated in a for loop based on its groups:
sequence_df = pd.DataFrame(sequence_profile)
figure = px.line(sequence_df, x = sequence_df["sample"], y = sequence_df["intensity"], color= sequence_df["method"], facet_col= sequence_df["group"])
Although it still needs more formatting, my plot now looks like this, which is works much better for my purposes:

how to remove generic content of matplotlib regardless of type plotted

I've looked around for a while and found a number of clever ways to remove content from a plot.
e.g. lines = blah, del lines[0], line gone.
but this obviously doesn't work for histograms, or imshow for instance.
Is there a way to clear the plotting area (i.e. not using clf()) without having to regenerate the entire figure. This requires you to have no strict knowledge of what is currently plotted but still be able to remove it. I am developing an application which uses the same area for plotting and I want a generic way to remove the content for different types of graphs I want to display. Some lines, some scatter, some hist etc.
Thanks.
Everything you can display on an axes is a subclass of Artist and have a member function remove (doc). All of the plotting functions (should) return the artist (or list of artists) that they add to the axes. Ex:
ln, = ax.plot(...) # adds a line
img = ax.imshow( ) # adds an image
ln.remove() # removes the line
img.remove() # removes the image
You will have to re-draw the canvas (plt.draw() or ax.figure.canvas.draw()) before the changes are visible.
You can get a list of all the artists in a given axes with
artist_list = ax.get_children()
If you want to remove everything from an axis,
ax.cla()

Matplotlib adding overlay labels to an axis

In matplotlib I wish to know the cleanest and most robust means of overlaying labels onto an axis. This is probably best demonstrated with an example:
While normal axis labels/ticks are placed every 5.00 units additional labels without ticks have been overlayed onto the axis (this can be seen at 1113.75 which partially covers 1114.00 and 1105.00 which is covered entirely). The labels also have the same font and size as their normal, ticked, counterparts with the background (if any) going right up to the axis (as a tick mark would).
What is the simplest way of obtaining this effect in matplotlib?
Edit
Following on from #Ken's suggestion I have managed to obtain the effect for an existing tick/label by using ax.yaxis.get_ticklines and ax.yaxis.get_ticklabels to both remove the tick marker and change the background/font/zorder of a label. However, I am unsure how best to add a new tick/label to an axis.
In other words I am looking for a function add_tick(ax.yaxis, loc) that adds a tick at location loc and returns the tickline and ticklabel objects for me to operate on.
I haven't ever tried to do that, but I think that the Artist tutorial might be helpful for you. In particular, the last section has the following code:
for line in ax1.yaxis.get_ticklines():
# line is a Line2D instance
line.set_color('green')
line.set_markersize(25)
line.set_markeredgewidth(3)
I think that using something like line.set_markersize(0) might make the markers have size zero. The difficult part might be finding the ones that need that done. It is possible that the line.xdata or line.ydata arrays might contain enough information to isolate the ones you need. Of course, if you are manually adding the tick marks, it is possible that as you do that the instance gets returned, so you can just modify them as you create them.
The best solution I have been able to devise:
# main: axis; olocs: locations list; ocols: location colours
def overlay_labels(main, olocs, ocols):
# Append the overlay labels as ticks
main.yaxis.set_ticks(np.append(main.yaxis.get_ticklocs(), olocs))
# Perform generic formatting to /all/ ticks
# [...]
labels = reversed(main.yaxis.get_ticklabels())
markers = reversed(main.yaxis.get_ticklines()[1::2]) # RHS ticks only
glines = reversed(main.yaxis.get_gridlines())
rocols = reversed(ocols)
# Suitably format each overlay tick (colours and lines)
for label,marker,grid,colour in izip(labels, markers, glines, rocols):
label.set_color('white')
label.set_backgroundcolor(colour)
marker.set_visible(False)
grid.set_visible(False)
It is not particularly elegant but does appear to work.

Python graph- change axis marker colours and legend border colours

I'm using Python to plot a couple of graphs and I'm trying to change the formatting and essentially 'brand' the graph. I've managed to change most things using pylab.rcParams[...], but I can't work out how to change the colour of the markers on the axes and the border around the legend. Any help would be much appreciated. The line below is an example of the type of code I've been using to edit other parts. Basically just lines taken from matplotlibrc, but I can't find them to change everything I want.
pylab.rcParams[axes.labelcolor' = '#031F73'
If you just want to use rcParams, the proper parameters are xticks.color and yticks.color. I can't seem to find a key for the legend frame color. You can set that (along with the tick colors) programmatically though.
import pylab
pylab.plot([1,2,3],[4,5,6], label ='test')
lg = pylab.legend()
lg.get_frame().set_edgecolor('blue')
ax = pylab.axes()
for line in ax.yaxis.get_ticklines():
line.set_color('blue')
for line in ax.xaxis.get_ticklines():
line.set_color('blue')
for label in ax.yaxis.get_ticklabels():
label.set_color('blue')
for label in ax.xaxis.get_ticklabels():
label.set_color('blue')
pylab.show()

Categories