I am aware of how to plot a line graph on top of scatter plot of the same data but is there a way to bring the line graph forward so it sits on top of the markers rather than behind?
Example code:
import numpy as np
x=np.array([1,2,3,4,5])
y=np.array([1,2,3,4,5])
plt.errorbar(x,y,xerr=0.1,yerr=0.1, fmt="x",markersize=5, color = "orange")
plt.plot(x,y)
This code outputs a scatter graph with a line graph behind it. When you increase the number of data points it becomes harder to see the line behind them all. Other than decreasing the marker size can I bring the line on top of all the points?
I think you are intending to draw things at different levels of z-order on the screen. This is done like such:
plt.plot(x,y, zorder=10)
Note 10 is arbitrarily large and this will likely plot on top of your legend too, so you may need to adjust it!
You can use the option barsabove=True. This places the error bars above the markers and the line is displayed on the top of error bars and markers. To highlight this effect, I am using a thick error bar. As you can see, the blue line lies above the error bars and markers. Use barsabove=False (default value) to see the difference.
x=np.array([1,2,3,4,5])
y=np.array([1,2,3,4,5])
plt.errorbar(x,y,xerr=0.1,yerr=0.1, linewidth=10, fmt="x",markersize=5, color = "orange", barsabove=True)
plt.plot(x,y)
Related
I have problems when drawing horizontal bar chart
firstly if we draw it in plt.bar
plt.figure(figsize=(8,5))
plt.bar(range_df.range_start, range_df.cum_trade_vol, width=30)
plt.show()
but if we draw it in plt.barh
plt.figure(figsize=(8, 5))
plt.barh(range_df.range_start, range_df.cum_trade_vol)
plt.show()
its either
or like:
The problem, I think, is because the crowded data that left too few gaps.
What can we do to properly draw the graph? (since we cannot set width with barh? or can we?)
Maybe another plot package?
Please do not reset the y axis value as the current value is important
The data can be downloaded at
https://drive.google.com/file/d/1y8fHazEFhVR_u2KL6uUsBqv0qmXOd2xT/view?usp=share_link
the notebook is at:
https://colab.research.google.com/drive/1MbjJE4B-mspDRqCYXnDf8hyFRK_uLmRp?usp=sharing
Thank you
I am somewhat unsure of what you are talking about. When writing the horizontal plot, you drop width parameter. There is an equivalent version for plt.barh which is height. So try
plt.barh(range_df.range_start, range_df.cum_trade_vol, height=30)
My codes are shown below
As you can see I am creating a histogram and a vertical line to show a certain threshold. However, I am getting the vertical line and the histogram on two separate graphs. how do I get them to show on the same graph.
be30dayChg is time series and I am creating histogram out of it(just an fyi if anyone interested)
be30dayChg = sec[['20yBE']].diff(30)
beVaR99Hist = be30dayChg.quantile(.01)
plt.axvline(x=np.asscalar(beVaR99Hist), color='r', linestyle='-')
be30dayChg.hist()
plt.show()
You can do something like this.
plt.axvline("line params")
plt.bar("Data", hist)
I am trying to match two lines visually in a plot in matplotlib, but am having trouble getting their linewidths to match up, as one is made through a patch. As a minimal working example, I have:
plt.axvline(3.2,linewidth=2,color='b')
plt.gca().add_patch(patches.FancyArrowPatch((3,3), (3,7), **dict(arrowstyle="Simple,tail_width=2,head_width=5,head_length=7"),color='b',edgecolor=None))
plt.ylim(0,10)
plt.xlim(0,5)
You can see that the arrow appears wider (and also appears fuzzier?). What can I do to fix this so that both appear the same width?
The arrow appears thicker as it is drawn as a path with a certain line width (mpl.rcParams['lines.linewidth'], usually 1.5). If you set lw to 0 the arroy tail have the same thickness as the vertical line:
plt.gca().add_patch(mpl.patches.FancyArrowPatch((3,3), (3,7), **dict(arrowstyle="Simple,tail_width=2,head_width=5,head_length=7"),color='b',edgecolor=None, lw=0 ))
The fuzziness is due to antialiasing, if you switch it off (aa=False) then the edges become sharper but the head doesn't look so nice.
All,
I'm trying to export figures in (roughly) a particular size so I can include them in high-res in my LaTeX document. When I draw the figure, the ylabel is cutoff (I assume because my figure is small, 2.7in wide). When I call tight_layout(), I get the labels fine, but now the axes are no longer center in the saved image. I need the axes centered above the caption, so I want the axes centered on the image.
I tried adding a second axis to the right side, but I couldn't figure out how to make the labels and ticks invisible for that axis.
Here is without tight_layout()
Here is with tight_layout()
Any idea how I can get the best of both worlds (everything visible, with the axes centered)?
Thanks!
I also encountered this problem and it seems there is no elegent way after I googled it. I ended up with the fig.subplots_adjust.
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([10,20,30])
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.patch.set_facecolor('silver')
fig.set_size_inches(w=3.5, h =3)
# %%
#fig.tight_layout()
plt.subplots_adjust(left=0.15, right=0.85, bottom=0.15, top=0.9)
fig.savefig('test.png')
But this will produce additional padding around the axes and tedious parameter-tuning...
while fig.tight_layout() produces:
It would be nice to test it on the code. But try playing with axes.set_position() as shown here: https://www.google.com/amp/s/www.geeksforgeeks.org/matplotlib-axes-axes-set_position-in-python/amp/
Disclaimer: I am very inexperienced using matplotlib and python in general.
Here is the figure I'm trying to make:
Using GridSpec works well for laying out the plots, but when I try to include a colorbar on the right of each row, it changes the size of the corresponding subplot. This seems to be a well known and unavoidable problem with GridSpec. So at the advice of this question: Matplotlib 2 Subplots, 1 Colorbar
I've decided to remake the whole plot using ImageGrid. Unfortunately the documentation only lists the options cbar_mode=[None|single|each] whereas I want 1 colobar per row. Is there a way to do this inside a single ImageGrid? or will I have to make 2 grids and deal with the nightmare of alignment.
What about the 5th plot at the bottom? Is there a way to include that in the image grid somehow?
The only way I can see this working is to somehow nest two ImageGrids into a GridSpec in a 1x3 column. this seems overly complicated and difficult so I don't want to build that script until I know its the right way to go.
Thanks for any help/advice!
Ok I figured it out. It seems ImageGrid uses subplot somehow inside it. So I was able to generate the following plot using something like
TopGrid = ImageGrid( fig, 311,
nrows_ncols=(1,2),
axes_pad=0,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="3%",
cbar_pad=0.0,
cbar_set_cax=True
)
<Plotting commands for the top row of plots and colorbar>
BotGrid = ImageGrid( fig, 312,
nrows_ncols=(1,2),
axes_pad=0,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="3%",
cbar_pad=0.0,
)
<Plotting commands for bottom row . . .>
StemPlot = plt.subplot(313)
<plotting commands for bottom stem plot>
EDIT: the whitespace in the color plots is intentional, not some artifact from adding the colorbars