简体   繁体   中英

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()

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:

在此处输入图像描述

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM