I have a figure with multiple subplots, some being data graphs and some images. The image data will typically determine the size of the axes automatically, which is good. However, when I add titles to the different subplots, the titles are a different vertical positions. Here is a (reduced) example:
import pylab as plt
plt.subplot(121)
plt.title('A')
plt.subplot(122)
plt.imshow(plt.randn(10, 10))
plt.title('B')
plt.show()
See below for the output:
As you can see, the titles (A and B) are at different vertical positions. I am aware that I could manually set the pad parameter of the title function, but I was wondering if there is an automatic way to do so as well.
I don't have much experience with Matplotlib, but if you change the line
plt.subplot(122)
to
plt.subplot(222)
you should get the result I think you want.
Related
I got a general issue with a plotting function using matplotlib.pyplot. I plot a set of stacked horizontal bar charts, the goal is to produce congruent figures, the embedded grid is suppose to fit, but the image gets resized, when I change the input data. However, if i plot the image without the legend, I receive the desired output. But I do want to include a legend of course !
The formatting lines I include are the following:
figure size
fig,ax = plt.subplots(1,figsize=(20,9))
grid definition
plt.grid(color="darkgrey")
legend defintion
ax.legend([handles[i] for i in order], [labels[i] for i in order],
bbox_to_anchor=((0.5, -0.15)), loc="upper center",fontsize="medium",ncol=5)
tight layout
fig.tight_layout()
store the image
fig.savefig(str(figname)+'.jpg',bbox_inches='tight',quality=95,dpi=300)
I am using jupyter-lab for plotting a dataframe.
fig = df.plot().get_figure()
fig.savefig("test.png")
Unfortunately, the surroundings of the plot (the space that is not between the x and y axis), where the coordinates are displayed are transparent, meaning a checkered grey-black pattern, which makes the coordinates practically unreadable. Is there any way of widening the non-transparent area so that the coordinates are included?
There are a couple of ways that you can achieve this:
Update the matplotlib rcParams:
import matplotlib as mpl
mpl.rcParams.update({"figure.facecolor": "white"})
this will affect all the plots after you set this parameter in this script.
Set the figure facecolor for a single figure:
fig = df.plot().get_figure()
fig.set_facecolor("white")
I created a stacked barchart using matplotlib.pyplot but there is no border around the graph so the title of the graph and axes are right up against the edge of the image and get cutoff in some contexts when I use it. I would like to add a small clear or white border around the graph, axes and title. repos_amount is a pandas DataFrame.
Here is my code:
colors = ["Green", "Red","Blue"]
repos_amount[['Agency','MBS','Treasury']].plot.bar(stacked=True, color=colors, figsize=(15,7))
plt.title('Total Outstanding Fed Repos Operations', fontsize=16)
plt.ylabel('$ Billions', fontsize=12)
Here is what the graph looks like:
I tried the suggestions from the link below and I could not figure out how to make it work. I'm not good with matplotlib yet so I would need help figuring out how to apply it to my code.
How to draw a frame on a matplotlib figure
Try adding plt.tight_layout() to the bottom of your code.
Documentation indicates that this tries to fit the titles, labels etc within the subplot figure size, rather than adding items around this figure size.
It can have undesirable results if your labels or headings are too big, in which case you would then need to look into the answers in this thread to adjust the specific box size of your chart elements.
Hi I'd like to recreate the following plot with matplotlib and pandas.
I started to use boxplot but i'm struggling to manipulate the kwargs.
Is there a simple way to use boxplot or do I need to recreate the chart enitrely.
One issue I had was also adding the current data?
Best regards
The boxplot from matplotlib has indeed some limitations. For you to have full control over how the plot looks I would advise using Patches to draw Rectangles for example (code from Rectangles link):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(
patches.Rectangle(
(0.1, 0.1), # (x,y)
0.5, # width
0.5, # height
)
)
fig1.savefig('rect1.png', dpi=90, bbox_inches='tight')
This is useful because you'll only need this and a normal plot command (for lines) in matplotlib to do a boxplot. This will give you immense control about color and shape and it's fairly easy to build. You also have text there you'll need for which you can use matplotlib text. The last thing are those markers which are very doable with a scatter.
A boxplot is a shape that tells you information such a minimum, maximum, and percentiles (25,50,75). You can calculate this very easily with numpy percentile.
The details of the plot (labels at the bottom, legend, title in box, and so on) can also be achieved but tinkering with labels, manually building a title box and so on.
It will give you some work but these are the commands you need.
I have to translate an image plotting script from matlab to matplotlib/pylab, and I'm trying to achieve the same effect as the matlab image below:
As you can see, the z order of the plots seem to be higher than the z order of the grid, so the markers are not hidden by the axes. However, I can't figure out a way to do the same with my matplotlib image:
I'm wondering if it is possible to get the same display without having to increase the limits of the y axis.
To get the marker to show beyond the axes you can turn the clipping off. This can be done using the keyword argument in the plot command clip_on=False.
For example:
import matplotlib.pyplot as plt
plt.plot(range(5), range(5), 'ro', markersize=20, clip_on=False, zorder=100)
plt.show()
This is a complete example of how to use the zorder kwarg: http://matplotlib.sourceforge.net/examples/pylab_examples/zorder_demo.html
Note that a higher z-order equates to a graph-element being more in the foreground.
For your second question, have a look at the figsize kwarg to instances of the Figure class: http://matplotlib.sourceforge.net/api/figure_api.html?highlight=figsize#matplotlib.figure.Figure
If you run into issues, please post some of your code and we'll be able to give more-detailed recommendations. Best of luck.
If you're plotting the lines one after the other, just change the order of the plotting calls and that would fix the z order.