英文:
Matplotlib bar plot with two different colors
问题
In a Dataframe column with 10 values, I am trying to create a bar plot with the first 5 being blue, and the remaining 5 red.
In 1: import matplotlib.pyplot as plt
In [2]: import pandas as pd
In [3]: df = pd.DataFrame({"x": range(10)})
In [4]: ax = df.iloc[:5].plot(kind="bar", color="blue")
In [5]: plt.show()
In [6]: df.iloc[5:].plot(kind="bar", color="grey", ax=ax)
Out[6]: <Axes: >
In [7]: ax.bar(df.index[5:].values, df.iloc[5:, 0].values, color="grey")
Out[7]: <BarContainer object of 5 artists>
\[5\] Shows the plot of the first 5 blue elements. I tried two ways of adding the second part, \[6\] and \[7\], but that was not successful. I tried using plt.show() which did not show anything. A final `ax.figure.savefig("fig.png")` shows a barplot of the last 5 elements in grey.
How do I get them into one figure?
I tried using the above code to generate the desired figure. Tried putting the same commands into a jupyter notebook yielding the same results.
英文:
In a Dataframe column with 10 values, I am trying to create a bar plot with the first 5 being blue, and the remaining 5 red.
In [1]: import matplotlib.pyplot as plt
In [2]: import pandas as pd
In [3]: df = pd.DataFrame({"x": range(10)})
In [4]: ax = df.iloc[:5].plot(kind="bar", color="blue")
In [5]: plt.show()
In [6]: df.iloc[5:].plot(kind="bar", color="grey", ax=ax)
Out[6]: <Axes: >
In [7]: ax.bar(df.index[5:].values, df.iloc[5:, 0].values, color="grey")
Out[7]: <BarContainer object of 5 artists>
[5] Shows the plot of the first 5 blue elements. I tried two ways of adding the second part, [6] and [7], but that was not successful. I tried using plt.show() which did not show anything. A final ax.figure.savefig("fig.png")
shows a barplot of the last 5 elements in grey.
How do I get them into one figure?
I tried using the above code to generate the desired figure. Tried putting the same commands into a jupyter notebook yielding the same results.
答案1
得分: 1
输出您想要的内容不太清楚。您是想要类似以下的东西吗:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'x': range(1, 11)})
ax = df['x'].plot(kind='bar', color=['blue']*5+['red']*5)
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论