I have a table like:
value type
10 0
12 1
13 1
14 2
Generate a dummy data:
import numpy as np
value = np.random.randint(1, 20, 10)
type = np.random.choice([0, 1, 2], 10)
I want to accomplish a task in Python 3 with matplotlib (v1.4):
value
type
, i.e. use different colors to differentiate typesidentity
for bins, i.e. the width of a bin is 1The questions are:
type
and draw colors from colormap (e.g. Accent
or other cmap in matplotlib)? I don't want to use named color (i.e. 'b', 'k', 'r'
)Note
pandas.plot
for two hours and failed to get the desired histogram.matplotlib.pyplot
, without import a bunch of modules such as matplotlib.cm
, matplotlib.colors
.In python, we plot histogram using plt. hist() method.
For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable. Here we customize our plot with two histograms with larger labels, title and legend using the label we defined.
The space between bars can be added by using rwidth parameter inside the “plt. hist()” function. This value specifies the width of the bar with respect to its default width and the value of rwidth cannot be greater than 1.
In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot.
For your first question, we can create a dummy column equal to 1, and then generate counts by summing this column, grouped by value and type.
For your second question you can pass the colormap directly into plot
using the colormap
parameter:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn
seaborn.set() #make the plots look pretty
df = pd.DataFrame({'value': value, 'type': type})
df['dummy'] = 1
ag = df.groupby(['value','type']).sum().unstack()
ag.columns = ag.columns.droplevel()
ag.plot(kind = 'bar', colormap = cm.Accent, width = 1)
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With