簡體   English   中英

Matplotlib 條形圖:與列表顏色不同的條形圖

[英]Matplotlib barchart: Bars in a different color from list

我正在嘗試使用 Python/Matplotlib 創建一個酒吧 plot。 這個想法是導入一個 csv, plot 條形圖,但根據列表中的條目選擇條形的顏色 - x 軸基本上包含一列年份,並且列表包含我想要的較短年份列表改變顏色。 當我手動輸入單個值而不是列表(參見“color1”)時,它可以工作,但不能使用列表。 我能做的最好的事情是在另一個 np.array 中添加要查找的年份並進行比較,但是我從 python 中得到的所有信息都警告我關於模棱兩可的結果並需要使用 a.any() - 我太過分了新手要真正理解。 如果有人知道我在這里做錯了什么,任何幫助將不勝感激,特別是因為這是我 python/matplotlib 體驗的第二天。 因此,我真的不想開始探索 pandas 作為選項,這里的一些解決方案使用它。 其他人使用簡單的 python 列表。 在這里,我需要使用一列 np.array 和 python 列表。

import matplotlib.pyplot as plt
import numpy as np

#import csv, first column is a list of years
with open("./data.csv") as data:
    x,y,z = np.genfromtxt((line.replace(',', '.') for line in data), delimiter=";", usecols=(0,1,2), unpack=True)

width = 0.35  #  width of bars
yearticks = [1990, 1998, 2008, 2021]            
color1 = ["red" if i != 1991 else "blue" for i in x]

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, y, width, label='y-axis', color=color1)
rects2 = ax.bar(x + width/2, z, width, label='z-axis')

ax.set_ylabel('ylabel')
ax.set_title('xlabel')
ax.set_xticks(yearticks)

這是你想要的? 我更新了代碼,以便它檢查 x(year) 是否在列表中並將 x 條繪制為藍色/紅色。 由於 x,y,z 數據不可用,因此使用隨機數據(前 3 行)。

x=np.random.randint(1990, 2020, size=(20))
y=np.random.randint(30, size=(20))
z=np.random.randint(30, 60, size=(20))

width = 0.35  #  width of bars
yearticks = [1990, 1998, 2008, 2021]            
color1 = ["red" if i in yearticks else "blue" for i in x]

fig, ax = plt.subplots(figsize=(20,5))
rects1 = ax.bar(x - width/2, y, width, label='y-axis', color=color1)
rects2 = ax.bar(x + width/2, z, width, label='z-axis')

ax.set_ylabel('ylabel')
ax.set_title('xlabel')
ax.set_xticks(yearticks)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM