在Python中为条形图在多个条形上设置不同的颜色?

时间:2018-07-19 07:08:35

标签: python bar-chart sensor

是否可以在Python中为条形图在多个条形上设置不同的颜色?我正在尝试从结构如下的文本文件中为参与者R1和R2显示不同的颜色:

2009-02-02  07:38:31.220809 M29 OFF
2009-02-02  07:38:31.430629 M37 OFF
2009-02-02  07:38:33.946559 M36 ON  R1_Personal_Hygiene end
2009-02-02  07:44:12.597919 M49 ON  R2_Bed_to_Toilet begin
2009-02-02  07:44:12.74531  M38 OFF
2009-02-02  07:44:12.886409 M46 OFF
2009-02-02  07:44:15.04394  M50 ON
2009-02-02  07:44:15.52659  M44 ON
2009-02-02  07:44:15.88134  M47 OFF
2009-02-02  07:44:16.091619 M47 OFF
2009-02-02  07:44:16.292619 M47 OFF
2009-02-02  07:44:18.04502  M48 OFF
2009-02-02  07:44:18.22705  M49 OFF
2009-02-02  07:44:18.79765  M43 ON
2009-02-02  07:44:20.825139 M28 ON
2009-02-02  07:44:21.16597  M42 ON

我能够对其进行硬编码,但是我正在逐行从文本文件中读取传感器数据并将其存储在数组中。我认为它与 colour 函数有关,但是我不知道如何在数组中使用它。到目前为止,这是我的代码:

# Import libraries
import collections
import matplotlib.pyplot as plt
from datetime import datetime

#Get user input
file_name = input('Enter File name: ')
file = open(file_name)
#Array of sensors
sensors = []

#Iterate through the file line by line
for line in file:
    words = line.split()
    #This line filters out the sensor data for the required time 
    interval
    if (datetime.strptime (words[1][0:7], "%H:%M:%S")) > 
    (datetime.strptime ("07:00:00", "%H:%M:%S")) and (datetime.strptime 
    (words[1][0:7], "%H:%M:%S")) < (datetime.strptime ("08:00:00", 
    "%H:%M:%S")):
        if words[3] == "ON":
            sensors.append(words[2])

count = collections.Counter(sensors)
print(count)

# Plot Graph and Set Y labels and X Labels
plt.bar(range(len(count)),count.values(),align='center')
plt.xticks(range(len(count)),count.keys())
plt.ylabel('Count')
plt.xlabel('Sensors')
plt.title('Motion Sensor Data')
plt.show()

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试将其添加到您的图例中:

AVCaptureDevice

然后您只需要弄清楚想要多少种颜色-老实说,在您的示例中,我并没有完全定义颜色的数量,因此,我只给出一个通用表达式。

import matplotlib.cm as cm

这是一个颜色数组,现在您可以使用如下索引访问颜色:

NrCol = #Enter formula or methode to calculate total number of colours needed 
colour = cm.rainbow(np.linspace(0,1,NrCol))

我没有得到您想要的东西,但是如果您说可以对其进行硬编码,则应该可以用这种颜色替换硬编码的颜色,并且应该没问题。

希望有帮助!干杯