我正在尝试使用Matplotlib创建堆积的条形图。该图似乎可以很好地堆叠,但是当我显示结果时出现了这些奇怪的空白。我在想这是因为我正在将“ bottom =” plt.bar属性设置为当前数据集,而从示例代码看来,您应该将“ bottom =”设置为先前数据集的总和。我所做的努力只产生了空白图表,因此我想最好还是上传显示带有多余空格的图表的代码。
有任何解决此问题的想法吗?
from pandas.api.types import CategoricalDtype
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('D:/GIT/GSURFizDataProcessing/fizdata/fizmay2019data.txt', sep="\t", header=None)
#df.to_csv('D:/GIT/GSURFizDataProcessing/fizdata/fizproblemdata.csv')
df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
df = df.loc[:,[0,1,2]]
df.columns = ['date', 'sensor', 'value']
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S.%f')
df['Day of Week'] = df['date'].dt.weekday_name
weekdays = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
cat_type = CategoricalDtype(categories=weekdays, ordered=True)
df['Day of Week'] = df['Day of Week'].astype(cat_type)
motionSensors = ["D8MotionA", "D14MotionA",
"D14MotionB",
"D15AMotionA", "D15BMotionA", "D15MotionA","D15MotionB",
"D15MotionC","D18MotionA","D21AMotionA","D21MotionA",
"D4MotionA","D6MotionA","D22MotionA"]
df = df[df['sensor'].isin(motionSensors)]
df['TimeDelta'] = 0
listOfColors = {}
for i in motionSensors:
listOfColors[i] = np.random.rand(3, )
usedLabels = []
for day in weekdays:
datasets = []
for sensor in motionSensors:
print("NEW SENSOR ", sensor)
parsedDf = df[(df['Day of Week']==day) & (df['sensor']==sensor)]
firstValue = parsedDf["value"].iloc[0]
if firstValue == "OFF":
parsedDf.drop(parsedDf.head(1).index, inplace=True)
# Get seconds
parsedDf['TimeDelta'] = parsedDf['date'].shift(-1) - parsedDf['date']
parsedDf.iloc[::2]
parsedDf = parsedDf[parsedDf['TimeDelta'] < timedelta(days=2)]
parsedDf.drop(parsedDf.tail(1).index, inplace=True)
parsedDf["TimeDelta"] / np.timedelta64(1, 's')
summed = parsedDf["TimeDelta"].sum()
summed = summed.total_seconds()
summed = summed / 3600
#labelText = sensor + ": " + ("%.2f" % sum) + " hrs"
#print(labelText)
if sensor in usedLabels:
plt.bar(day, summed, 0.4, color=listOfColors[sensor], bottom=summed)
else:
plt.bar(day, summed, 0.4, color=listOfColors[sensor], label=sensor, bottom=summed)
usedLabels.append(sensor)
datasets.append(summed)
plt.title("Fiz May 2019 Usage Data")
plt.ylabel("Time Spent (hr)")
ax = plt.subplot(111)
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
plt.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8))
plt.show()
答案 0 :(得分:0)
结果是条形图重叠了:一开始它们甚至都没有堆叠。