Matplotlib - transform bbox - matplotlib

I printed some text into a plot. Now I want to make a copy of this text and move it to different coordinates. I guess I'll have to do this with tranform, but did not find a solution yet.
here is the code:
props = dict( facecolor='#DDDDDD', alpha=1,edgecolor='#FFFFFF',boxstyle="Square,pad=0.5")
text2=plt.text(4, 4, "text",va='top', ha='left',bbox=props)
plt.draw()
bb2=text2.get_bbox_patch().get_window_extent().transformed(ax.transData.inverted()).get_points()

To move the text to different coordinates you only need:
text2.set_position((new_x,new_y))
you could also use:
text2.set_x(new_x)
text2.set_y(new_y)

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

How to Superimpose on 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

How to control mouseover text in matplotlib

When you mouseover an image shown with imshow, you can mouseover the image to inspect its RGB values. The bottom-right corner of the matplotlib window (sharing space with the toolbar), shows the image coordinates and RGB values of the pixel being pointed at:
x = 274.99 y = 235.584 [.241, .213, .203]
However, when I mouseover a quiver plot, it only shows the x and y coords of the pointer, but not the value of the 2D vector being pointed at. Is there a way to get the vector values to show up?
I would be fine with writing a custom mouse event handler, if I only knew how to set that bit of text in the matplotlib window.
There were times when the information about the color value was not present by default. In fact I think the current version is based on some code that came up in Stackoverflow on some question about that feature.
I quickly found those two questions:
matplotlib values under cursor
Interactive pixel information of an image in Python?
The idea would be to change the function that is called when the mouse hovers the axes. This function is stored in ax.format_coord. So a possible solution is to write your custom function to return the desired output based on the input coordinates, e.g. something like
def format_coord(x, y):
try:
z = # get value depending on x,y, e.g. via interpolation on grid
# I can't fill this because the kind of data is unknown here
return "x: {}, y: {}, z: {}".format(x,y,z)
except:
return "x: {}, y: {}".format(x,y)
ax.format_coord = format_coord

Matplotlib annotate doesn't work on log scale?

I am making log-log plots for different data sets and need to include the best fit line equation. I know where in the plot I should place the equation, but since the data sets have very different values, I'd like to use relative coordinates in the annotation. (Otherwise, the annotation would move for every data set.)
I am aware of the annotate() function of matplotlib, and I know that I can use textcoords='axes fraction' to enable relative coordinates. When I plot my data on the regular scale, it works. But then I change at least one of the scales to log and the annotation disappears. I get no error message.
Here's my code:
plt.clf()
samplevalues = [100,1000,5000,10^4]
ax = plt.subplot(111)
ax.plot(samplevalues,samplevalues,'o',color='black')
ax.annotate('hi',(0.5,0.5), textcoords='axes fraction')
ax.set_xscale('log')
ax.set_yscale('log')
plt.show()
If I comment out ax.set_xcale('log') and ax.set_ycale('log'), the annotation appears right in the middle of the plot (where it should be). Otherwise, it doesn't appear.
Thanks in advance for your help!
It may really be a bug as pointed out by #tcaswell in the comment but a workaround is to use text() in axis coords:
plt.clf()
samplevalues = [100,1000,5000,10^4]
ax = plt.subplot(111)
ax.loglog(samplevalues,samplevalues,'o',color='black')
ax.text(0.5, 0.5,'hi',transform=ax.transAxes)
plt.show()
Another approach is to use figtext() but that is more cumbersome to use if there are already several plots (panels).
By the way, in the code above, I plotted the data using log-log scale directly. That is, instead of:
ax.plot(samplevalues,samplevalues,'o',color='black')
ax.set_xscale('log')
ax.set_yscale('log')
I did:
ax.loglog(samplevalues,samplevalues,'o',color='black')