Is It Possible To Set Transparency When Using LineCollection in Matplotlib? - python

There are a number of helpful posts for using LineCollections in Matplotlib.
I have working code, but am having trouble figuring out how to set the transparency of the lines. For example, in Pandas it's as easy as doing:
df.plot(kind='line',alpha=.25)
However, I chose the LineCollection method because I want to plot a dataframe with >15k lines and the above example does not work.
I've tried adding ax.set_alpha(.25) in my code:
fig, ax = plt.subplots()
ax.set_xlim(np.min(may_days), np.max(may_days))
ax.set_ylim(np.min(may_segments.min()), np.max(may_segments.max()))
line_segments = LineCollection(may_segments,cmap='jet')
line_segments.set_array(may_days)
ax.add_collection(line_segments)
ax.set_alpha(.05)
ax.set_title('Daily May Data')
plt.show()
but there is no change.
Unfortunately I cannot provide a sample of the data with which I'm working; however, I've found the second example this Matplotlib gallery doc to be easy to copy.

You do it the same way you'd do it in pandas.
line_segments = LineCollection(may_segments, cmap='jet', alpha=0.05)

Related

Unable to Plot 3d Function Using Matplotlib

I am trying to plot a 3d function in python using matplotlib. For some reason I get the error "Invalid syntax (pyflakes E)" in the second line of the code provided when trying to plot it. I got this part from another person, and this works for them. The packages from matplotlib I have installed are mplot3d, cm, and Subplot. Perhaps there is another package I need?
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(projection='3d')
https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html#:~:text=In%C2%A0%5B3%5D%3A-,fig%20%3D%20plt.figure()%0Aax%20%3D%20plt.axes(projection%3D%273d%27),-With%20this%20three
It seems that you need to use ax = plt.axes(projection = 3d)

Matplotlib not showing histogram correctly when saving figure

Using matplotlib, I am plotting 2 histograms in one figure. The goal is to add them to a Latex document later. I am interested in the difference between the two, so I use a low transparency and plot them on top of each other. In Spyder, when I plot inline, the image looks fine. See wanted plot
When I export the image as a PNG using plt.savefig(), the image looks like this. However, this does not work well in Latex documents as the scaling gets ruined. When I try to export it as a PDF file, the bars of the histogram seem to overlap, making it seem like it has edges, like in ugly plot.
I think the cause of the problem is due to the vector format, when zooming in and out of the PDF, the overlap changes. When zoomed in completely, it looks identical to the PNG, when zoomed out the overlap becomes much larger. I would be very grateful if anyone knew the solution to this.
Things I have tried already:
changing linewidth/edgecolor
changing the matplotlibrc file
changing the distance of the bins using rwidth
Code I am using:
binwidth = (np.max(prediction) - np.min(prediction)) / (2*I**(1/3))
kwargs = dict(alpha=0.5, bins=np.arange(min(prediction), max(prediction) + binwidth, binwidth))
fig_path = '***.pdf'
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.hist(prediction.flatten(), **kwargs, label = 'NN')
ax.hist(hedging_error, **kwargs, label = 'BS')
ax.set_xlim((-3,3))
ax.set_xlabel('Hedging error')
ax.set_ylabel('Count')
ax.legend()
fig.savefig(fig_path)
To remove the bin edges use plt.hist(..., histtype='stepfilled')
https://matplotlib.org/stable/gallery/statistics/histogram_histtypes.html

Convert matplotlib plot to numpy list to show using opencv2

so I am making 4 types of plots in matplotlib through functions. Those include Pie Charts, Line Charts, Scatter Plot and area graphs. I want to get a numpy array of it, so I can display it using opencv2 or something else on django. I have tried this so far:
import matplotlib.pyplot as plt
import numpy as np
# Make a random plot...
fig = plt.figure()
fig.add_subplot(111)
# If we haven't already shown or saved the plot, then we need to
# draw the figure first...
fig.canvas.draw()
# Now we can save it to a numpy array.
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
But the problem is I cannot use a plot here, I have to use a figure which I don't want to use. I tried doing plt.plot([1,2,3,4,5]) for line graph as a test, but it turns out it returns a list, while I need a figure to use the tostring_rgb() What should be the alternative to this?
EDIT:
Suggested in comments for another question, I am not wanting to make a figure, I want to make a normal Plot with plt.plot() of line graph, and also plt.pie()

Using plots as objects in python (jupyter lab)?

I just started switching from R to python, and have been a bit confused by the way plots are handled.
In R, I would generate a scatter plot this way:
myPlot <- ggplot(myData, aes(x=x, y=y)) + geom_point(). myPlot will be treated as an object, I can save it, copy it, pass it, or just plot it later.
However, in python I couldn't figure out how to do it. For example, when I use:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'X': [1,2,3],
'Y': [4,5,6]
})
ax = df.plot(kind="scatter", x='X', y='Y')
all I want to do here is to save the plot to an object, so that it can be easily plotted later without executing all the code again (it's easy to redo in this dummy case but my data is far more complicated)
It seems that I was able to save some information into "ax", as suggested online, but I couldn't figure out how to reproduce the plot with the object "ax".
Thank you so much~
Have a look at the visualization section of the pandas docs.
ax in your example indeed holds the plot object. Depending on your environment you can save it to a figure or display it inline.
The easiest way is just to plt.show().

Matplotlib/Latex issues when using \odot as marker

I'm trying to use the latex symbol \odot as a marker in a scatter plot but I also need latex style ticks, but for some reason these two are not playing well together. I can successfully use marker=$\\odot$ with usetex=False, like this, but when I set it equal to true (to get the tick font right), I get ! LaTeX Error: File 'type1cm.sty' not found. I've already gone through to make sure I have the sty file installed and in the correct directory and that I have all the dependencies installed (as suggested here). Plus, I can still have usetex=True and use any of the normal pyplot markers, just not anything involving math font, but can I can have \odot in the label for the legend. Ive also already tried appending the rc params with amsmath but still keep getting the type1cm error. I've also tried using the raw string literal to no avail.
So basically when usetex=True, I can use math symbols in the label for the legend, just not as the actual marker. Has anyone experienced this issue before?
My current work around involves just plotting a large unfilled circle and overplotting a small filled circle (basically simulating the odot). Then I run into an issue with the legend so I basically have to create a transparent legend showing the large unfilled circles and then plot the smaller filled circles behind it by hand like this which ends up wonky, but this has the axes tick font I need. This becomes very frustrating if I have to change axes limits though, because I have to repeat the process of figuring out where to plot the small filled circles all over again.
Does anyone know if there is a better work around than this? Would it be possible to use the overplotting scheme like I have been, but then create a custom proxy artist to display the \odot symbol (in the different colors/sizes) in the legend?
Mac OSX, matplotlib 1.4.2, python 2.7, matplotlib is using pdfTeX thru TeX Live 2017/Mac Ports 2017
Edit: Here is my code
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
f, ax1 = plt.subplots(1,1)
x = np.arange(20)
y = x
ax1.scatter(x, y, marker='$\\odot$', edgecolors='b', s=200, label = 'Test') #used with usetex=False
#ax1.scatter(x, y, marker='o', edgecolors='b', s=200, label = 'Test') #used with usetex=True
ax1.tick_params(labelsize=24)
leg = ax1.legend(scatterpoints=1, loc='lower right', borderaxespad=0., handletextpad=0.)#, fontsize=18) # borderpad=0.,)
I'm not sure how much I can help without seeing your code, but this worked for me:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
x1 = [1,2]; x2 = [1,2]
y1 = [1,1]; y2 = [2,2]
mpl.rc('text', usetex = True)
fig, ax = plt.subplots(1,1)
ax.scatter(x1,y1, label='A1', marker=r'$\odot$',s=150, c='b')
ax.scatter(x2,y2, label='A2', marker=r'$\odot$',s=50, c='b')
ax.set_xlim(0,3)
ax.set_ylim(0,3)
ax.legend()
fig.show()
If this doesn't help let me know!

Categories