Python孪生图古怪图

问题描述

编辑:该图现在已修复,但在绘制图例时遇到了麻烦。它仅显示其中1个地块的图例。如下图所示

我试图绘制一个带有孪生子的双轴图,但是我面临一些困难,如下图所示。

欢迎任何输入!如果您需要任何其他信息,我们很乐意为您提供这些信息。

enter image description here

与绘制z轴之前的原始图像相比。

enter image description here

我不确定为什么我的图像最初那样绘制我的次要y轴(粉红色的线)时是这样的,收盘价图可以完美地看到,但现在看起来像是切掉的。

可能是由于以下提供的数据所致。

链接到testing1.csv:https://filebin.net/ou93iqiinss02l0g

我当前拥有的代码

# read csv into variable
sg_df_merged = pd.read_csv("testing1.csv",parse_dates=[0],index_col=0)

# define figure
fig = plt.figure()

fig,ax5 = plt.subplots()
ax6 = ax5.twinx()

x = sg_df_merged.index
y = sg_df_merged["Adj Close"]
z = sg_df_merged["Singapore"]

curve1 = ax5.plot(x,y,label="Singapore",color = "c")
curve2 = ax6.plot(x,z,label = "Face Mask Compliance",color = "m")
curves = [curve1,curve2]

# labels for my axis
ax5.set_xlabel("Year")
ax5.set_ylabel("Adjusted Closing Value ($)")
ax6.set_ylabel("% compliance to wearing face mask")
ax5.grid #not sure what this line does actually

# set x-axis values to 45 degree angle
for label in ax5.xaxis.get_ticklabels():
    label.set_rotation(45)
ax5.grid(True,color = "k",linestyle = "-",linewidth = 0.3)

plt.gca().legend(loc='center left',bBox_to_anchor=(1.1,0.5),title = "Country Index")
plt.show(); 

最初,我认为这是由于我的excel具有整个空白行,但此后我删除了可以找到的行here

此外,我尝试进行插值,但是以某种方式不起作用。任何对此的建议都非常欢迎

解决方法

  • 仅删除所有NaN所在的行。 NaN仍然有很多行。
  • 为了使matplotlib在两个数据点之间绘制连接线,这些点必须连续。
  • plot API未连接NaN值之间的数据
  • 这可以通过将pandas.Series转换为DataFrame并使用.dropna来解决。
  • 请确保已删除x,因为它与yz的索引长度不匹配。它们在.dropna之后更短。
  • y现在是一个单独的数据框,其中使用了.dropna
  • z也是一个单独的数据框,其中使用了.dropna
  • 该图的x-axis是相应的索引。
# read csv into variable
sg_df_merged = pd.read_csv("test.csv",parse_dates=[0],index_col=0)

# define figure
fig,ax5 = plt.subplots(figsize=(8,6))
ax6 = ax5.twinx()

# select specific columns to plot and drop additional NaN
y = pd.DataFrame(sg_df_merged["Adj Close"]).dropna()
z = pd.DataFrame(sg_df_merged["Singapore"]).dropna()

# add plots with markers
curve1 = ax5.plot(y.index,'Adj Close',data=y,label="Singapore",color = "c",marker='o')
curve2 = ax6.plot(z.index,'Singapore',data=z,label = "Face Mask Compliance",color = "m",marker='o')

# labels for my axis
ax5.set_xlabel("Year")
ax5.set_ylabel("Adjusted Closing Value ($)")
ax6.set_ylabel("% compliance to wearing face mask")
    
# rotate xticks
ax5.xaxis.set_tick_params(rotation=45)

# add a grid to ax5
ax5.grid(True,color = "k",linestyle = "-",linewidth = 0.3)

# create a legend for both axes
curves = curve1 + curve2
labels = [l.get_label() for l in curves]
ax5.legend(curves,labels,loc='center left',bbox_to_anchor=(1.1,0.5),title = "Country Index")

plt.show()

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...