Alex Luthor
Alex Luthor

Reputation: 55

Python matplotlib bar graph color

I'm trying to display some data in bar graph using xticks. The code below displays my bars in different colors. My question is how do I make the whole graph in one color? Thanks in advance.

import matplotlib.pyplot as plt

data = (5)
data_2 = (6)

plt.bar(1, data)
plt.bar(2, data_2)

plt.xticks([1,2], ('Hello', 'World'))

plt.show()

Upvotes: 1

Views: 165

Answers (2)

Red
Red

Reputation: 27567

Here is how:

import matplotlib.pyplot as plt

data = (5)
data_2 = (6)

plt.bar([1,2], [data,data_2])

plt.xticks([1,2], ('Tom', 'Dick'))

plt.show()

Or add color keyword argument:

import matplotlib.pyplot as plt

data = (5)
data_2 = (6)
color = 'red'
plt.bar(1, data, color=color)
plt.bar(2, data_2, color=color)

plt.xticks([1,2], ('Tom', 'Dick'))

plt.show()

Output:

enter image description here

Upvotes: 1

rpanai
rpanai

Reputation: 13437

I think that there is an easier way to obtain the same color for all bars.

import matplotlib.pyplot as plt

x = [1,2]
x_ticks = ['Tom', 'Dick']
y = [5,6]
plt.bar(x, y)
plt.xticks(x, x_ticks);

In case you want to use pandas

import pandas as pd

df = pd.DataFrame({'x': [1,2],
                   'y': [5, 6],
                   'name': ['Tom', 'Dick']})

ax = df.plot(x='x', y='y', kind='bar')
ax.set_xticks(df.index)
ax.set_xticklabels(df["name"], rotation=0);

or even easier

df.plot(x='name', y='y', kind='bar', rot=0);

Upvotes: 0

Related Questions