Why can't I see labels using pyplot [duplicate] - python

When I execute the following code, it doesn't produce a plot with a label.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5)
plt.plot(x, x*1.5, label='Normal')
Numpy version is '1.6.2'
Matplotlib version is '1.3.x'
Any ideas as to why this is happening?

You forgot to display the legend:
...
plt.legend(loc='best')
plt.show()

Related

How to create specific plots using Pandas and then store them as PNG files?

So I am trying to create histograms for each specific variable in my dataset and then save it as a PNG file.
My code is as follows:
import pandas as pd
import matplotlib.pyplot as plt
x=combined_databook.groupby('x_1').hist()
x.figure.savefig("x.png")
I keep getting "AttributeError: 'Series' object has no attribute 'figure'"
Use matplotlib to create a figure and axis objects, then tell pandas which axes to plot on using the ax argument. Finally, use matplotlib (or the fig) to save the figure.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Sample Data (3 groups, normally distributed)
df = pd.DataFrame({'gp': np.random.choice(list('abc'), 1000),
'data': np.random.normal(0, 1, 1000)})
fig, ax = plt.subplots()
df.groupby('gp').hist(ax=ax, ec='k', grid=False, bins=20, alpha=0.5)
fig.savefig('your_fig.png', dpi=200)
your_fig.png
Instead of using *.hist() I would use matplotlib.pyplot.hist().
Example :
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
y =[10, 20,30,40,100,200,300,400,1000,2000]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = Values')
plt.title('my plot')
ax.legend()
plt.show()
fig.savefig('tada.png')

xticks don't show in matplotlib

I'm trying to plot out a dictionary data with matplotlib in python3.6, macOS.
I want the keys of the dict to be printed as sticks but they are not showing actually.
My code is as below:
import pandas as pd
import glob
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
%matplotlib inline
figure(num=None, figsize=(500, 100), dpi=80, facecolor='w', edgecolor='k')
D = info_dict
x = list(D.keys())
y = list(D.values())
plt.bar(x,y)
plt.xticks(range(len(D)), list(D.values()), rotation='vertical')
plt.margins(0.2)
plt.subplots_adjust(bottom=0.15)
plt.show()
And the plotted one is like this:

Plotting multiple figures in a loop

I am trying to plot a diagram inside a loop and I expect to get two separate figures, but Python only shows one figure instead. In fact, it seems Python plots the second figure over the first one. This is the code I am using:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y = np.arange(0,10)
for _ in range(2):
plt.plot(x,y)
plt.show()
It worth noting that I am working with Python 2.7 in PyCharm environment. Any kind of advice is appreciated.
Try the following:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y = np.arange(0,10)
for _ in range(2):
plt.figure() # add this statement before your plot
plt.plot(x,y)
plt.show()
This could do:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y = np.arange(0,10)
f, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, y)
ax2.plot(x, y)
plt.show()

Matplotlib graph with typical linestyle not showing

I want a very simple plot:
import matplotlib.pyplot as plt
import numpy as np
for t in np.linspace(0,2*np.pi,100):
plt.plot(np.cos(t), np.sin(t), color='blue', linestyle='-', linewidth=7)
plt.show()
But nothing is appearing. I just get an empty plot. Where is my error?
Just plot the whole arrays:
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0,2*np.pi,100):
plt.plot(np.cos(t), np.sin(t), color='blue', linestyle='-',linewidth=7)
plt.show()
Each call to plt.plot within the for loop is plotting a separate 'line' that consists on only a single point.
if you want the code to work you should plot points instead of lines.
for t in np.linspace(0,2*np.pi,100): plt.plot(np.cos(t), np.sin(t), 'k.')

How to generate a colorbar for manually colored plots in matplotlib?

Suppose I need to control line colors myself for some reason, for example:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
for i in np.linspace(0, 1, 100):
plt.plot([i,i+1,i+2], color=mpl.cm.viridis(i))
How to generate a colorbar for such a plot?
You would need to create a colorbar without any reference axes. This can be done with the matplotlib.colorbar.ColorbarBase class. See also this example from the gallery.
To use this, you need to create a new axis in the plot, where the colorbar should sit in; one way of doing this is to use make_axes_locatable.
Here is a complete example.
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
for i in np.linspace(0, 1, 9):
plt.plot([i,i+1,i+2], color=mpl.cm.viridis(i))
divider = make_axes_locatable(plt.gca())
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
cb1 = mpl.colorbar.ColorbarBase(ax_cb, cmap=mpl.cm.viridis, orientation='vertical')
plt.gcf().add_axes(ax_cb)
plt.show()

Categories