Matplotlib 条形图,使用两种不同的颜色。

huangapple go评论52阅读模式
英文:

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({&quot;x&quot;: range(10)})

In [4]: ax = df.iloc[:5].plot(kind=&quot;bar&quot;, color=&quot;blue&quot;)

In [5]: plt.show()

In [6]: df.iloc[5:].plot(kind=&quot;bar&quot;, color=&quot;grey&quot;, ax=ax)
Out[6]: &lt;Axes: &gt;

In [7]: ax.bar(df.index[5:].values, df.iloc[5:, 0].values, color=&quot;grey&quot;)
Out[7]: &lt;BarContainer object of 5 artists&gt;

[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(&quot;fig.png&quot;) 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()

Matplotlib 条形图,使用两种不同的颜色。

英文:

The output of what you want is unclear. Do you want to get something like:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({&#39;x&#39;: range(1, 11)})
ax = df[&#39;x&#39;].plot(kind=&#39;bar&#39;, color=[&#39;blue&#39;]*5+[&#39;red&#39;]*5)
plt.show()

Matplotlib 条形图,使用两种不同的颜色。

huangapple
  • 本文由 发表于 2023年2月19日 21:52:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定