brack_barh dy non d ofter

发布于 2025-01-24 00:52:26 字数 2377 浏览 2 评论 0原文

我正在尝试创建一个破碎的小号,以显示不同作物类型的生长。第一部分需要介绍种植月,然后是生长期和收获期。不幸的是,我无法提供正确的酒吧顺序。我想创建一条对角线的收获期,以表明可以进行整整一年的收获。由于奇怪的顺序,我的代码提供了我也无法将正确的标签连接到我的y轴。

看来代码在启动正确起作用,然后突然出现问题。

这是我的代码:

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.read_excel("twee.xlsx")

df[['Plant1','Plant2']] = df.Plant.str.split(',',expand=True)
df[['Grow1','Grow2']] = df.Grow.str.split(',',expand=True)
df[['Harv1','Harv2']] = df.Harv.str.split(',',expand=True)

columnlist = ['Plant1','Plant2','Grow1','Grow2','Harv1','Harv2']

for i in columnlist:
    df[i] = df[i].astype(int)

df = df.sort_values(by=['Harv1'],ascending=True)

y = []
for i in range(10,((1+len(df.Species))*10),10):
    y.append((i,9))

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
xaxis = []
for i in range(len(months)):
    xaxis.append(i)

species = df.Species.tolist()

yaxis = []
a = 15
for i in range(len(species)):
    b = a + i*10
    yaxis.append(b)

fig, ax = plt.subplots()
for index, row in df.iterrows():
    temp = ([row.Plant1,row.Plant2], [row.Grow1,row.Grow2], [row.Harv1,row.Harv2])
    temp2 = [1,2,3]
    a=0
    for j in temp:
        temp2[a] =  ( int(j[0]), int(j[1]) )
        a += 1 
    ax.broken_barh(temp2, y[index],
               facecolors=('#F4A460', '#32CD32', '#FF7F50'), label=species[index])

ax.set_ylim(5, max(yaxis)+20)
ax.set_xlim(0, max(xaxis))
ax.set_xlabel('Months')
ax.set_xticks(xaxis, labels=months)
ax.set_yticks(yaxis, labels=species)
ax.grid(False)
plt.title("Seasonal Planting East Capitol Urban Farm")
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')
plt.show()

非常感谢您的帮助!

编辑: 这是我使用的数据。

I am trying to create a broken barplot showing the growth of different crop types. The first part needs to present the planting month followed by the growing period and the harvesting period. Unfortunately, I am not able to provide the right order of the bars. I want to create a diagonal line of the harvesting periods so it shows that the whole year through harvesting can take place. Due to the strange order, my code provides I am also not able to connect the right labels to my y-axis.

enter image description here

It seems that the code functions at the start correctly and then suddenly something goes wrong.

Here is my code:

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.read_excel("twee.xlsx")

df[['Plant1','Plant2']] = df.Plant.str.split(',',expand=True)
df[['Grow1','Grow2']] = df.Grow.str.split(',',expand=True)
df[['Harv1','Harv2']] = df.Harv.str.split(',',expand=True)

columnlist = ['Plant1','Plant2','Grow1','Grow2','Harv1','Harv2']

for i in columnlist:
    df[i] = df[i].astype(int)

df = df.sort_values(by=['Harv1'],ascending=True)

y = []
for i in range(10,((1+len(df.Species))*10),10):
    y.append((i,9))

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
xaxis = []
for i in range(len(months)):
    xaxis.append(i)

species = df.Species.tolist()

yaxis = []
a = 15
for i in range(len(species)):
    b = a + i*10
    yaxis.append(b)

fig, ax = plt.subplots()
for index, row in df.iterrows():
    temp = ([row.Plant1,row.Plant2], [row.Grow1,row.Grow2], [row.Harv1,row.Harv2])
    temp2 = [1,2,3]
    a=0
    for j in temp:
        temp2[a] =  ( int(j[0]), int(j[1]) )
        a += 1 
    ax.broken_barh(temp2, y[index],
               facecolors=('#F4A460', '#32CD32', '#FF7F50'), label=species[index])

ax.set_ylim(5, max(yaxis)+20)
ax.set_xlim(0, max(xaxis))
ax.set_xlabel('Months')
ax.set_xticks(xaxis, labels=months)
ax.set_yticks(yaxis, labels=species)
ax.grid(False)
plt.title("Seasonal Planting East Capitol Urban Farm")
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')
plt.show()

I would really appreciate your help!

EDIT:
This is the data I used.

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春庭雪 2025-01-31 00:52:26

当您对数据框进行排序时,索引不会重置。因此,随着您在行迭代时,行被搞砸了。您需要将排序更改为 - df = df.sort_values(by = ['harv1'],ascending = true).Reset_index(drop = true)。这将重置新排序列表的索引。

此处更新的代码和图形。有关将来的参考,请以一种方式粘贴表,可以将数据复制到文本或Excel文件

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.read_excel("twee.xlsx")

df[['Plant1','Plant2']] = df.Plant.str.split(',',expand=True)
df[['Grow1','Grow2']] = df.Grow.str.split(',',expand=True)
df[['Harv1','Harv2']] = df.Harv.str.split(',',expand=True)

columnlist = ['Plant1','Plant2','Grow1','Grow2','Harv1','Harv2']

for i in columnlist:
    df[i] = df[i].astype(int)

df = df.sort_values(by=['Harv1'],ascending=True).reset_index(drop=True)

y = []
for i in range(10,((1+len(df.Species))*10),10):
    y.append((i,9))

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
xaxis = []
for i in range(len(months)):
    xaxis.append(i)

species = df.Species.tolist()

yaxis = []
a = 15
for i in range(len(species)):
    b = a + i*10
    yaxis.append(b)

fig, ax = plt.subplots()
for index, row in df.iterrows():
    temp = ([row.Plant1,row.Plant2], [row.Grow1,row.Grow2], [row.Harv1,row.Harv2])
    temp2 = [1,2,3]
    a=0
    for j in temp:
        temp2[a] =  ( int(j[0]), int(j[1]) )
        a += 1 
    ax.broken_barh(temp2, y[index],
               facecolors=('#F4A460', '#32CD32', '#FF7F50'), label=species[index])

ax.set_ylim(5, max(yaxis)+20)
ax.set_xlim(0, max(xaxis))
ax.set_xlabel('Months')
ax.set_xticks(xaxis)
ax.set_xticklabels(months)
ax.set_yticks(yaxis)
ax.set_yticklabels(species)
ax.grid(False)
plt.title("Seasonal Planting East Capitol Urban Farm")
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')
fig.set_size_inches(12,25)
plt.show()

“在此处输入图像说明”

When you are sorting the dataframe, the indexes are not reset. So, as you are iterating through the rows, the rows are getting messed up. You need to change the sort to - df = df.sort_values(by=['Harv1'],ascending=True).reset_index(drop=True). This will reset the index to the new sorted list.

The updated code and graph as here. For future reference, please paste the table in a way one can copy the data into a text or excel file

import pandas as pd 
import matplotlib.pyplot as plt 

df = pd.read_excel("twee.xlsx")

df[['Plant1','Plant2']] = df.Plant.str.split(',',expand=True)
df[['Grow1','Grow2']] = df.Grow.str.split(',',expand=True)
df[['Harv1','Harv2']] = df.Harv.str.split(',',expand=True)

columnlist = ['Plant1','Plant2','Grow1','Grow2','Harv1','Harv2']

for i in columnlist:
    df[i] = df[i].astype(int)

df = df.sort_values(by=['Harv1'],ascending=True).reset_index(drop=True)

y = []
for i in range(10,((1+len(df.Species))*10),10):
    y.append((i,9))

months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
xaxis = []
for i in range(len(months)):
    xaxis.append(i)

species = df.Species.tolist()

yaxis = []
a = 15
for i in range(len(species)):
    b = a + i*10
    yaxis.append(b)

fig, ax = plt.subplots()
for index, row in df.iterrows():
    temp = ([row.Plant1,row.Plant2], [row.Grow1,row.Grow2], [row.Harv1,row.Harv2])
    temp2 = [1,2,3]
    a=0
    for j in temp:
        temp2[a] =  ( int(j[0]), int(j[1]) )
        a += 1 
    ax.broken_barh(temp2, y[index],
               facecolors=('#F4A460', '#32CD32', '#FF7F50'), label=species[index])

ax.set_ylim(5, max(yaxis)+20)
ax.set_xlim(0, max(xaxis))
ax.set_xlabel('Months')
ax.set_xticks(xaxis)
ax.set_xticklabels(months)
ax.set_yticks(yaxis)
ax.set_yticklabels(species)
ax.grid(False)
plt.title("Seasonal Planting East Capitol Urban Farm")
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')
fig.set_size_inches(12,25)
plt.show()

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文