英文:
have multiple lines in the same graph in python
问题
请帮我,我已经能够绘制一个图表,使用以下代码:
df = pd.Series(data1, name='y').rename_axis('x').reset_index()
df.plot(kind='scatter', x='x', y='y')
对于一个字典类型,例如 `{ '2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41 }`。
如何处理多个数据/字典,即不同的值但相同的键,例如:
data1 = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41}
data2 = {'2022-01-30': 124, '2022-01-31': 142, '2022-02-01': 745}
data3 = {'2022-01-30': 4, '2022-01-31': 1, '2022-02-01': 7}
另外,如何在图表中标记所绘制的线?
英文:
Please I need help I have been able to plot a graph using
df = pd.Series(data1, name='y').rename_axis('x').reset_index()
df.plot(kind='scatter' , x='x' , y='y' )
for a dictionary type {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41 }
How can i have it multiple data/dictionary i.e. different values but the same key e.g.
data1 = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41 }
data2 = {'2022-01-30': 124, '2022-01-31': 142, '2022-02-01': 745 }
data3 = {'2022-01-30': 4, '2022-01-31': 1, '2022-02-01': 7 }
Also how can i label the lines drawn within the graph
答案1
得分: 4
你可以考虑以不同的方式构建DataFrame,并使用折线图(而不是散点图):
df = pd.DataFrame([data1, data2, data3]).T.rename_axis(index='x', columns='y')
df.plot()
输出:
如果你还想要为这些线条添加标签,可以从列表中添加它们:
df = (pd.DataFrame([data1, data2, data3], index=['data1', 'data2', 'data3'])
.T.rename_axis(index='x', columns='y')
)
df.plot()
输出:
英文:
You might just want to build the DataFrame in a different way and use a line plot (not scatter):
df = pd.DataFrame([data1, data2, data3]).T.rename_axis(index='x', columns='y')
df.plot()
Output:
If you also want labels for the lines, add them from a list:
df = (pd.DataFrame([data1, data2, data3], index=['data1', 'data2', 'data3'])
.T.rename_axis(index='x', columns='y')
)
df.plot()
Output:
答案2
得分: 2
以下是翻译好的部分:
如果需要设置每一列的标签,可以通过使用字典构造DataFrame:
d1 = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41 }
d2 = {'2022-01-30': 124, '2022-01-31': 142, '2022-02-01': 745 }
d3 = {'2022-01-30': 4, '2022-01-31': 1, '2022-02-01': 7 }
df = pd.DataFrame({'a': d1, 'b': d2, 'c': d3})
如果需要传递标签列表和DataFrame列表:
df = pd.DataFrame(dict(zip(['a', 'b', 'c'], [d1, d2, d3]))
print(df)
最后使用DataFrame.plot
绘制图表:
df.plot()
英文:
If need set labels of each column create DataFrame by constructor with dictionaries:
d1 = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41 }
d2 = {'2022-01-30': 124, '2022-01-31': 142, '2022-02-01': 745 }
d3 = {'2022-01-30': 4, '2022-01-31': 1, '2022-02-01': 7 }
df = pd.DataFrame({'a': d1,'b': d2, 'c': d3})
If need pass lists of labels and list of DataFrames:
df = pd.DataFrame(dict(zip(['a','b','c'], [d1, d2, d3])))
print (df)
a b c
2022-01-30 50 124 4
2022-01-31 152 142 1
2022-02-01 41 745 7
Last plot by DataFrame.plot
:
df.plot()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论