3

Example array:

a=np.array([1,2,3,4,4,4,2,1,1,1,1])

I want to create a histogram from the array, and if I use matplotlib.pyplot's histogram:

import matplotlib.pyplot as plt
plt.hist(a,bins=[1,2,3,4,5])

I get this:

number of x

How do I get the columns in different colors? and how do i get labels, like if a green column the legend shows number 1 is green.

I suspect I might create four different datasets, but that I can't get to work..

1
  • Are all your data points integers? Commented Jun 17, 2015 at 8:50

1 Answer 1

3

Instead of directly calling plt.hist , try using subplot and plot a histogram inside that , like this -

import matplotlib.pyplot as plt
# define window size, output and axes
fig, ax = plt.subplots(figsize=[8,6])

# set plot title
ax.set_title("Some title")

# set x-axis name
ax.set_xlabel("X-Label")

# set y-axis name
ax.set_ylabel("Y-Label")

# create histogram within output
N, bins, patches = ax.hist(data, bins=50, color="#777777") #initial color of all bins

# Iterate through all histogram elements
# each element in this interation is one patch on the histogram, where:
# - bin_size - number of records in current bin
# - bin - value of current bin (x-axis)
# - patch - a rectangle, object of class matplotlib.patches.Patch
# more details on patch properties: [visit this link][1]
for bin_size, bin, patch in zip(N, bins, patches):
    if bin_size == <some number>:
        patch.set_facecolor("<some color like #FF000>")
        patch.set_label("something")
plt.show()
Sign up to request clarification or add additional context in comments.

3 Comments

Nope, it gets me this error: ValueError: color kwarg must have one color per dataset
Reduce the color array by 1 color, there are only 4 bins
Updated answer, please try that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.