I'm a beginner in the world of python programming and I'm having a really hard time figuring out how to tackle my problem.
The problem is when I created a plot using loop in python with matplotlib and mpld3, the plot is as I expected it to be but the legend of the plot is really wrong because the legends were overlapping with each other. The legend of the plot will be displayed for the latest data only because other data's legend is overlapped on it.
Below is the picture of my plot:
This is the code to create the plot and legend in loop:
plt.rcParams.update({'font.size': 13})
fig, ax = plt.subplots()
for i in range(3,5):
rd1 = pd.read_sql_query("SELECT press, rs FROM basic_chart WHERE
cs = "+str(i), app.config['SQLALCHEMY_DATABASE_URI'])
print(rd1)
pt = ax.plot(rd1['press'],rd1['rs'],'-o')
plugins.connect(fig, plugins.InteractiveLegendPlugin([pt],[str(i)]))
html = mpld3.fig_to_html(fig)
I think that the main problem is on the interactive legend code but I did not manage to figure out the right way to correct it. I really hope experts can help me in this problem.
plt.rcParams.update({'font.size': 13})
fig, ax = plt.subplots()
for i in range(3,5):
rd1 = pd.read_sql_query("SELECT press, rs FROM basic_chart WHERE
cs = "+str(i), app.config['SQLALCHEMY_DATABASE_URI'])
print(rd1)
pt = ax.plot(rd1['press'],rd1['rs'],'-o')
axhandles, axlabels = ax.get_legend_handles_labels()
plugins.connect(fig, plugins.InteractiveLegendPlugin(axhandles, axlabels))
html = mpld3.fig_to_html(fig)
By having the plugins.connect in the loop, you are creating two separate legends.
After plotting, get the handles and labels from the plot and use that in the call to the InteractiveLegendPlugin.
Related
I have already plotted two figures separately in a single jupyter notebook file, and exported them.
What I want is to show them side by side, but not plot them again by using matplotlib.pyplot.subplots.
For example, in Mathematica, it's easier to do this by just saving the figures into a Variable, and displaying them afterwards.
What I tried was saving the figures, using
fig1, ax1 = plt.subplots(1,1)
... #plotting using ax1.plot()
fig2, ax2 = plt.subplots(1,1)
... #plotting using ax2.plot()
Now, those fig1 or fig2 are of type Matplotlib.figure.figure which stores the figure as an 'image-type' instance. I can even see them separately by calling just fig1 or fig2 in my notebook.
But, I can not show them together as by doing something like
plt.show(fig1, fig2)
It returns nothing since, there wasn't any figures currently being plotted.
You may look at this link or this, which is a Mathematica version of what I was talking about.
assuming u want to merge those subplots in the end.
Here is the code
import numpy as np
import matplotlib.pyplot as plt
#e.x function to plot
x = np.linspace(0, 10)
y = np.exp(x)
#almost your code
figure, axes = plt.subplots(1,1)
res_1, = axes.plot(x,y) #saving the results in a tuple
plt.show()
plt.close(figure)
figure, axes = plt.subplots(1,1)
res_2, = axes.plot(x,-y) #same before
plt.show()
#restructure to merge
figure_2, (axe_1,axe_2) = plt.subplots(1,2) #defining rows and columns
axe_1.plot(res_1.get_data()[0], res_1.get_data()[1]) #using the already generated data
axe_2.plot(res_2.get_data()[0], res_2.get_data()[1])
#if you want show them in one
plt.show()
Not quite sure what you mean with:
but not plot them again by using matplotlib.pyplot.subplots.
But you can display two figures next to each other in a jupyter notebook by using:
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0] = ... # Code for first figure
ax[1] = ... # Code for second figure
plt.show()
Or above each other:
fig, ax = plt.subplots(nrows=2, ncols=1)
ax[0] = ... # Top figure
ax[1] = ... # Bottom figure
plt.show()
I'm pretty new to Python. I'm trying to plot a box plot for a sample data
I'm trying to plot box plots of mean value of the shared data. I got that part of the code. I'm also trying to plot standard error values on this box plot using yerr().
My code:
data3=pd.read_csv('demo1.csv')
names=['brow', 'harr', 'hage', 'buch', 'mcre']
d=[data3['brow'].mean(),data3['harr'].mean(),data3['hage'].mean(),data3['buch'].mean(),data3['mcre'].mean()]
N=len(data3['co'])
l=math.sqrt(N)
k=[(data3['brow'].std())/l,(data3['harr'].std())/l,(data3['hage'].std())/l,(data3['buch'].std())/l,(data3['mcre'].std())/l,(data3['phil'].std())/l,(data3['moor'].std())/l]
fig, ax = plt.subplots()
plt.bar(names,d)
plt.bar(len(names),d,yerr=k,align='center',alpha=0.5,ecolor='black',capsize=10)
Im getting an image such as this
But I want the black lines to be against each bar graph and not as a new bar in the plot with all of them together. How can I change this. Am I using the plt the wrong way? Please help.
I don't understand what you were trying to do with your second call to plt.bar()
import math
names=['brow', 'harr', 'hage', 'buch', 'mcre']
data3 = pd.DataFrame({n: np.random.normal(loc=np.random.randint(5,10), scale=np.random.randint(1,10), size=(100,)) for n in names})
d=data3[names].mean()
N=100
l=math.sqrt(N)
k=data3[names].std()/l
fig, ax = plt.subplots()
plt.bar(names,d,yerr=k,align='center',alpha=0.5,ecolor='black',capsize=10)
I have created a figure in one part of the code as follows:
n = arange(51)
fig3 = plt.figure()
plt.semilogy(n,a1mag,'ro')
Now, i want to add another plot to this figure at a later part of the code. Is there some way to access fig3 while plotting?
It would be recommendable to either stay completely in the pyplot state-machine or comlpetely in the object oriented API; mixing the two causes just headaches.
pyplot
plt.figure(3)
plt.semilogy(x,y,'ro')
# .. do other stuff
# reactivate figure 3
plt.figure(3)
plt.plot(x,z)
object-oriented API
fig3, ax3 = plt.subplots()
ax3.semilogy(x,y)
# .. do other stuff
# plot to ax3
ax3.plot(x,z)
I'm trying to reproduce the following chart:
But I'm not sure if's actually possible to create such a plot using Python,R or Tableau.
Here is my first attempt using Plotly in R:
Do you have any suggestion for creating such a chart?
You can use R and de package highcharter to create a plot like this one:
spiderweb plot
the plot js code is in www/highcharts.com/demo/polar-spider
While I was working on creating this plot with matplotlib, someone mentioned that I can create this chart using Excel! in less than 2 minutes, so I didn't complete the code but anyway as I already figure out how should I create different elements of the plot in matplotlib, I put the code here in case anyone wants to create such a thing.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
#Adding grids
for rad in reversed(range(1,10)): #10 is maximum of ranks we need to show
ax1 = fig1.add_subplot(111,aspect = 'equal')
ax1.add_patch(
patches.RegularPolygon(
(0,0), #center of the shape
11, #number of vertices
rad,
fill=False,
ls='--',
))
plt.xlim(xmin = -10,xmax=10)
plt.ylim(ymin = -10,ymax=10)
fig1.show()
#plotting the trend
plt.scatter(xs,ys) #xs = list of x coordinates, the same for ys
for k in range(len(xs)-1):
x, y = [xs[k], xs[k+1]], [ys[k], ys[k+1]]
plt.plot(x, y,color = 'b')
plt.grid(False)
plt.show()
Result plot
(As I said the code doesn't create the whole trends, labels,...but it's pretty much all you need to create the plot)
I've created this plot, but it doesn't extend all the way across the figure for some reason. Can anyone help explain why?
Chart =
Code =
fig, ax = plt.subplots()
ax.plot(trip.index, trip.gas, marker='.',linestyle='-')
plt.xticks(np.arange(min(trip.index), max(trip.index), 7))
ax.set_xticklabels(map(str, ax.get_xticks()/7))
plt.xlabel('Week #')
plt.ylabel('Trip Cost ($)')
Matplotlib tends to include some space around the data. If you don't want that, you can adjust the axis ranges manually. This can be done via
plt.xlim(min(trip.index),max(trip.index))