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)
Related
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()
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)
I am using Holoviews for creating a visual dashboard and I want to create a Dynamic Tree Map within it. I tried finding documents, but I did not find any documentation of TreeMaps in the official Holoviews.
I then used Squarify library for plotting the TreeMaps but the Only Problem I am facing is that, I am not able to deploy these treemaps on server. When I start the server this Error message Pops up.
File "C:\Users\Nisarg.Bhatt\WinPython\python-3.6.5.amd64\lib\site-
packages\holoviews\plotting\util.py", line 236, in initialize_dynamic
dmaps = obj.traverse(lambda x: x, specs=[DynamicMap])
AttributeError: 'AxesSubplot' object has no attribute 'traverse'
CODE for TreeMap:
cmap = matplotlib.cm.Blues
mini=min(data["Quarter"])
maxi=max(data["Quarter"])
norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
#colors = [cmap(norm(value)) for value in data]
data1=data[0:1]
labels = [(label) for label in zip(data.Quarter,data.Company)]
fig = plt.figure(figsize=(20, 10))
plots=squarify.plot(sizes=data["month"],label= labels, color=
["red","blue","green"],alpha=.8)
new_plot= renderer.app(plots)
When this is executed, The TreeMaps are created in the Jupyter NoteBook.
QUERY:
1. Is there some other way of plotting TreeMap using just holoviews like hv.Curve or hv.Bars
How to solve this server issue.
Thanks in Advance.
Regards,
Nisarg
Use a lower level library as bokeh (holoviews compatible) where you can plot rectangles as squarify does.
#plotting TreeMap using squarify.plot
data = [8,3,4,2]
df = pd.DataFrame(data, columns=['nb_people'])
label=df.groupby(pd.cut(df["nb_people"], np.array([0,2,5,np.inf]),include_lowest=True,labels=['Group A','Group B','Group C'])).groups
squarify.plot(sizes=df['nb_people'], label=label, alpha=1)
plt.show()
squarify
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!
I am writing a script in Python (.py file) and I am using Matplotlib to plot an array.
I want to add a legend with a formula to the plot, but I haven't been able to do it.
I have done this before in IPython or the terminal. In this case, writing something like this:
legend(ur'$The_formula$')
worked perfectly. However, this doesn't work when I call my .py script from the terminal/IPython.
The easiest way is to assign the label when you plot the data,
e.g.:
import matplotlib.pyplot as plt
ax = plt.gca() # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')
ax.legend()
When writing code for labels it is:
import pylab
# code here
pylab.plot(x,y,'f:', '$sin(x)$')
So perhaps pylab.legend('$latex here$')
Edit:
The u is for unicode strings, try just r'$\latex$'