I have a question regarding creating a chart in Python using matplotlib and then deleting it to create a fresh chart. I find that when I create a chart called 'firstscatter' and then put in a print statement to print it to my Python console in Spyder, it prints the chart which is fine. However I want the chart to be deleted after it has been printed so that I can have a fresh 'secondscatter' chart printed.
So all in all what I want to see is the firstscatter chart printed, then deleted, and then the secondscatter chart printed.
How do I amend my code below to see both charts printed after running the code?
Thanks a lot and really appreciate your help.
import numpy as np
from numpy import random
import pandas as pd
from matplotlib import pyplot as plt
x = random.rand(30)
print (x)
y = random.rand(30)
print (y)
z = random.rand(50)
print (z)
firstscatter = plt.scatter(x,y,s = z * 777)
print (firstscatter)
firstscatter.remove()
secondscatter = plt.scatter(x,y,s = z*777, c='Chartreuse')
print (secondscatter)
When using Matplotlib, you must use plt.show() to show the current figure. In your case:
import numpy as np
from numpy import random
import pandas as pd
from matplotlib import pyplot as plt
x = random.rand(30)
print (x)
y = random.rand(30)
print (y)
z = random.rand(50)
print (z)
plt.scatter(x,y,s = z * 777)
plt.show()
plt.scatter(x,y,s = z*777, c='Chartreuse')
plt.show()
Instead of plt.show(), you can use plt.clf() to clear the current figure.
Related
I have the statement and I really don't understand the s= part. I know it sets the area of the plot but is it taking the data from pop_2007 and raising it to 1^6 to create the area ?
df.plot(kind='scatter', x='gdp_2007', y='lifeExp_2007', s=df['pop_2007']/1e6)
I'm trying to understand the area of a plot better and the s=
The 's' parameter in the pandas dataframe plot function is changing the size of the markers in your scatter plot. See these two outputs where I change the 's' value from 1 to 100. So right now, your plot is taking the value in the df['pop_2007'] column and dividing it by 1e6 to get your value for the marker size.
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
df.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=1)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Plot with s=1
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
df.plot(kind = 'scatter', x = 'Duration', y = 'Maxpulse', s=100)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Plot with s=100
Test it out here: https://www.w3schools.com/python/pandas/trypandas.asp?filename=demo_pandas_plot_scatter2
import numpy as np
from matplotlib_venn import venn2, venn2_circles, venn2_unweighted
from matplotlib_venn import venn3, venn3_circles
from matplotlib import pyplot as plt
plt.title(print("Shared",Signature_1, 'and',Signature_2, 'and',Signature_3))
venn3(subsets = (len(NameA), len(NameB), len(shared_A_B), len(NameC), len(shared_A_C),
len(shared_C_B), len(shared_A_B_C)), set_labels = (Signature_1, Signature_2, Signature_3), alpha = 0.5)
plt.show()
This code produces titles for plots in jupyter notebook only. When I run the .py script in Anaconda prompt only the plot is visible. How would I go about getting the titles to appear in the plot window? I realized because these are formatted to take variables [plt.title(print("title",variable,etc.)] that they do not work in command line. Any suggestions would be appreciated
You can use the .format method to include a variable into the print/title.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,10)
y = x**2
plt.plot(x,y)
variable ='IamVar'
Signature_1='one'
Signature_2='two'
Signature_3='three'
# \n stands for newline
plt.suptitle("Moving title - {} and {},{} \n set=({},{})".format(Signature_1,Signature_2,Signature_3,len(x),len(y))
,size=8,x=0.3, y=0.6)
plt.show()
I need to plot an accurate line graph through matplotlib but I only get a y=x graph. And the y-axis tick values are jumbled up.
import numpy as np
import matplotlib.pyplot as plt
title = "Number of Flats Constructed"
data = np.genfromtxt('C:\data/flats-constructed-by-housing-and-development-board-annual.csv',
skip_header=1,
dtype=[('year','i8'),('flats_constructed','U50')], delimiter=",",
missing_values=['na','-'],filling_values=[0])
x = data['year']
y = data['flats_constructed']
plt.title('No. of Flats Constructed over the Years')
#plt.plot(data['year'], data['flats_constructed'])
plt.plot(x, y)
plt.show()
I received a y=x graph instead of a jagged graph reflecting the values.
Actual output
Sample of expected output
Your mistake is at ('flats_constructed','U50').
Give it as ('flats_constructed','i8') itself. You read it as string when you gave U50.
from io import StringIO
import numpy as np
s = StringIO(u"1977,30498\n1978,264946\n1979,54666\n1980,54666")
data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','i8')], delimiter=",",skip_header=0)
data
plt.plot(data['myint'],data['myfloat'])
plt.show()
I am unable to display images in iPython from matplotlib, an image appears for a split of a second in a pop up window instead of inline and then closes immediately. nothing appears in the iPython console which is inside Spyder.
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import style
style.use('fivethirtyeight')
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slop_and_intercept (xs,ys):
m = ( ((mean(xs)*mean(ys))-mean(xs*ys)) /
((mean(xs)**2)-mean(xs**2)) )
b = mean(ys)-m*mean(xs)
return m,b
m,b = best_fit_slop_and_intercept(xs,ys)
print (m,b)
regression_line = [m*x + b for x in xs ]
print (regression_line)
predict_x = 9
predict_y = predict_x*m + b
plt.scatter(predict_x,predict_y, color = 'g')
plt.scatter(xs,ys)
plt.plot(xs, regression_line)
plt.show()
You can type %matplotlib inline inside the iPython console to generate your plots within the console inside spyder. You can also type %matplotlib qtto get an interactive window.
Your code snippet works for me with both settings. Failing that you can go to [preferences>iPython console>Graphics>Graphics backend] to adjust the graphics defaults and settings to see if that fixes the problem.
I would like to:
pylab.figure()
pylab.plot(x)
pylab.figure()
pylab.plot(y)
# ...
for i, figure in enumerate(pylab.MagicFunctionReturnsListOfAllFigures()):
figure.savefig('figure%d.png' % i)
What is the magic function that returns a list of current figures in pylab?
Websearch didn't help...
Pyplot has get_fignums method that returns a list of figure numbers. This should do what you want:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(100)
y = -x
plt.figure()
plt.plot(x)
plt.figure()
plt.plot(y)
for i in plt.get_fignums():
plt.figure(i)
plt.savefig('figure%d.png' % i)
The following one-liner retrieves the list of existing figures:
import matplotlib.pyplot as plt
figs = list(map(plt.figure, plt.get_fignums()))
Edit: As Matti Pastell's solution shows, there is a much better way: use plt.get_fignums().
import numpy as np
import pylab
import matplotlib._pylab_helpers
x=np.random.random((10,10))
y=np.random.random((10,10))
pylab.figure()
pylab.plot(x)
pylab.figure()
pylab.plot(y)
figures=[manager.canvas.figure
for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
print(figures)
# [<matplotlib.figure.Figure object at 0xb788ac6c>, <matplotlib.figure.Figure object at 0xa143d0c>]
for i, figure in enumerate(figures):
figure.savefig('figure%d.png' % i)
This should help you (from the pylab.figure doc):
call signature::
figure(num=None, figsize=(8, 6),
dpi=80, facecolor='w', edgecolor='k')
Create a new figure and return a
:class:matplotlib.figure.Figure
instance. If num = None, the
figure number will be incremented and
a new figure will be created.** The
returned figure objects have a
number attribute holding this number.
If you want to recall your figures in a loop then a good aproach would be to store your figure instances in a list and to call them in the loop.
>> f = pylab.figure()
>> mylist.append(f)
etc...
>> for fig in mylist:
>> fig.savefig()
Assuming you haven't manually specified num in any of your figure constructors (so all of your figure numbers are consecutive) and all of the figures that you would like to save actually have things plotted on them...
import matplotlib.pyplot as plt
plot_some_stuff()
# find all figures
figures = []
for i in range(maximum_number_of_possible_figures):
fig = plt.figure(i)
if fig.axes:
figures.append(fig)
else:
break
Has the side effect of creating a new blank figure, but better if you don't want to rely on an unsupported interface
I tend to name my figures using strings rather than using the default (and non-descriptive) integer. Here is a way to retrieve that name and save your figures with a descriptive filename:
import matplotlib.pyplot as plt
figures = []
figures.append(plt.figure(num='map'))
# Make a bunch of figures ...
assert figures[0].get_label() == 'map'
for figure in figures:
figure.savefig('{0}.png'.format(figure.get_label()))