How to Superimpose on Matplotlib - matplotlib

I want to draw a triangle with two points inside using matplotlib. Here is the code I'm using:
plt.figure()
triangleEdges = np.array([[0,0],[1,0],[0.5,0.5*np.sqrt(3)]])
colors = ['red', 'green', 'blue']
t1 = plt.Polygon(triangleEdges, facecolor="none",
edgecolor='black', linewidth=2)
t1.set_facecolor('xkcd:salmon')
plt.gca().add_patch(t1)
drawSoftmaxPoint('blue',100,np.array([0.2,0.1,0.7]) )
drawSoftmaxPoint('red',100,np.array([0.5,0.1,0.7]))
plt.show()
Picture
According to the code, there should be two points inside the triangle, but it looks like the background is covering them. How can I make them visible?
Thank you!

you could use alpha and z-order in your polygon to make it happen (from the doc of matplotlib). just try to set the alpha value between 0 and 1 to check if you can see your points. and then maybe use z-order on your different elements to make sure the fill of the polygon is deepest (most behind). example of zorder:
https://matplotlib.org/gallery/misc/zorder_demo.html

Related

How to add text into a plot in pyqtgraph like matplotlib.plot.text()

Like the title said, I want to add a text into a graph which I used pyqtgraph to plot, but I didn't find any function like matplotlib.plot.text() which I could set the text and even position in the graph.
self.plt_1.setLabel('left', 'CDF')
self.plt_1.setLabel('bottom', 'Delay', units='ms')
self.plt_1.setXRange(0, 200)
self.plt_1.setYRange(0, 1)
self.plt_1.setWindowTitle('DL CDF Curve')
self.plt_1.setMouseEnabled(x=False, y=False)
self.plt_1.setMenuEnabled(False)
self.plt_1.setText(30, 20, str(self.x_dl_5g_flag))
I tried this, but it doesn't work in my case, does anyone know how to do it in pyqtgraph? thanks
self.text = pg.TextItem(str(self.x_dl_5g_flag))
self.plt_1.addItem(self.text)
self.text.setPos(30,20)
If you want to add text to a graph and define its position on the plot in coordinates relative to the plot canvas (not data coordinates) you can use LabelItem instead of TextItem, something along the following lines (with pyqtgraph imported as pg):
self.text_label = pg.LabelItem("Your text")
self.text_label.setParentItem(self.plt_1.graphicsItem())
self.text_label.anchor(itemPos=(0.4, 0.1), parentPos=(0.4, 0.1))

How do I stretch our the horizontal axis of a matplotlib pyplot?

I'm creating a colour map which has 64 horizontal data points and 3072 vertical. When I plot it, the scaling on both axes is the same and so the horizontal axis is super squished and tiny, and I can't get any information from it. I've tried changing the figsize parameter but nothing changes the actual plot, only the image that contains it. Any ideas on how to change my plot so that the actual length of the axes are the same? Below is my plotting code:
def plot_plot(self, data, title="Pixel Plot"):
pixel_plot = plt.imshow(data)
plt.title(title)
plt.colorbar(pixel_plot)
plt.show(pixel_plot)
thanks in advance!
I think you want the aspect option in plt.imshow().
So something like plt.imshow(data, aspect=0.1) or plt.imshow(data, aspect='equal')
See this solution: https://stackoverflow.com/a/13390798/12133280

colorbars for grid of line (not contour) plots in matplotlib

I'm having trouble giving colorbars to a grid of line plots in Matplotlib.
I have a grid of plots, which each shows 64 lines. The lines depict the penalty value vs time when optimizing the same system under 64 different values of a certain hyperparameter h.
Since there are so many lines, instead of using a standard legend, I'd like to use a colorbar, and color the lines by the value of h. In other words, I'd like something that looks like this:
The above was done by adding a new axis to hold the colorbar, by calling figure.add_axes([0.95, 0.2, 0.02, 0.6]), passing in the axis position explicitly as parameters to that method. The colorbar was then created as in the example code here, by instantiating a ColorbarBase(). That's fine for single plots, but I'd like to make a grid of plots like the one above.
To do this, I tried doubling the number of subplots, and using every other subplot axis for the colorbar. Unfortunately, this led to the colorbars having the same size/shape as the plots:
Is there a way to shrink just the colorbar subplots in a grid of subplots like the 1x2 grid above?
Ideally, it'd be great if the colorbar just shared the same axis as the line plot it describes. I saw that the colorbar.colorbar() function has an ax parameter:
ax
parent axes object from which space for a new colorbar axes will be stolen.
That sounds great, except that colorbar.colorbar() requires you to pass in a imshow image, or a ContourSet, but my plot is neither an image nor a contour plot. Can I achieve the same (axis-sharing) effect using ColorbarBase?
It turns out you can have different-shaped subplots, so long as all the plots in a given row have the same height, and all the plots in a given column have the same width.
You can do this using gridspec.GridSpec, as described in this answer.
So I set the columns with line plots to be 20x wider than the columns with color bars. The code looks like:
grid_spec = gridspec.GridSpec(num_rows,
num_columns * 2,
width_ratios=[20, 1] * num_columns)
colormap_type = cm.cool
for (x_vec_list,
y_vec_list,
color_hyperparam_vec,
plot_index) in izip(x_vec_lists,
y_vec_lists,
color_hyperparam_vecs,
range(len(x_vecs))):
line_axis = plt.subplot(grid_spec[grid_index * 2])
colorbar_axis = plt.subplot(grid_spec[grid_index * 2 + 1])
colormap_normalizer = mpl.colors.Normalize(vmin=color_hyperparam_vec.min(),
vmax=color_hyperparam_vec.max())
scalar_to_color_map = mpl.cm.ScalarMappable(norm=colormap_normalizer,
cmap=colormap_type)
colorbar.ColorbarBase(colorbar_axis,
cmap=colormap_type,
norm=colormap_normalizer)
for (line_index,
x_vec,
y_vec) in zip(range(len(x_vec_list)),
x_vec_list,
y_vec_list):
hyperparam = color_hyperparam_vec[line_index]
line_color = scalar_to_color_map.to_rgba(hyperparam)
line_axis.plot(x_vec, y_vec, color=line_color, alpha=0.5)
For num_rows=1 and num_columns=1, this looks like:

How can I draw axes with a 45 degree rotation?

I have a set of 7x4 plots arranged in a grid using subplot. I now want to add diagonal axes on top of these.
I know you can superpose axes on top of previously made subplots by setting the background to 'none':
ax = fig.add_subplot(111)
ax.set_axis_bgcolor('none')
But I can't find a rotated axis thing. Currently I'm trying to use a top view 3D axes, but I'm far from a usable solution there.
I'm willing to accept drawing the axis+ticks by hand, if this is the only way possible.
EDIT: using the floating_axis module, I was able to draw rotated (and sheared) axes, but unable to edit the ticks, which is very necessary for what I need. The following snippet demonstrates adding a floating_axis to an existing figure fig. Any manipulation of the axes' ticks fails.
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
trafo = Affine2D().skew_deg(-10,-10).rotate_deg(45)
grid_helper = floating_axes.GridHelperCurveLinear(trafo, extremes=(0, 4, 0, 4))
artistax = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
artistax.set_axis_bgcolor('none')
artistax.axis["top"].set_visible(False)
artistax.axis["right"].set_visible(False)
fig.add_subplot(artistax)

matplotlib draw ellipse contour

I am trying to draw something similar:
The main idea is to draw ellipses with different color in some specific range, for example from [-6, 6].
I have understood that plt.contour function can be used. But I do not understand how to generate lines.
I personally wouldn't do this with contour as you then need to add information about the elevation which I don't think you want?
matplotlib has Ellipse which is a subclass of Artist. The following example adds a single ellipse to a plot.
import matplotlib as mpl
ellipse = mpl.patches.Ellipse(xy=(0, 0), width=2.0, height=1.0)
fig, ax = plt.subplots()
fig.gca().add_artist(ellipse)
ax.set_aspect('equal')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
You then need to research how to get the effect you are looking for, I would have a read of the docs in general making things transparent is done through alpha.