python - Mix of line and scatter plots from pandas dataframe in a single plot using the tick frequency of the first plot only
问题描述
I am wanting to compare data within a dataframe, plotting some of the data as lines, and other columns as scatter. My actual data is a combination of model output and observations, I want the observations to be scatter, and the model to be lines.
The observations have a LOT of Nan values (most times steps do not have an observation).
This MWE duplicates the issue I'm having
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(40)]
df = pd.DataFrame(data = {
"Time": date_list,
"Chocolate": np.random.rand(40),
"Strawberry": np.random.rand(40),
"Fake Chocolate": np.random.rand(40),
"Fake Strawberry": np.random.rand(40),
})
df.iloc[3,3] = np.nan
ax1 = df.plot(x = 'Time', y = ["Chocolate","Strawberry"])
ax1 = df.plot(x = 'Time', y = ["Chocolate","Strawberry"])
ax2 = df.plot.scatter(x = 'Time', y = ['Fake Chocolate'], marker = '^', ax = ax1)
ax3 = df.plot.scatter(x = 'Time', y = ['Fake Strawberry'], marker = '*', ax = ax1, color = '#ff7f0e')
I want to have the x-axis like in the first plot, so taking the style of the line plot where you don't have EVERY date trying to print in a tiny space. How do I do this?
I am using ax1.set
to set the x and y-axis labels.
and if I can sneak in a second question, why is it possible to do multiple lines using y = []
but not possible for the scatter plots?
解决方案
Just add plt.xticks(rotation=45)
to the end of your script and you will be fine.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(40)]
df = pd.DataFrame(data = {
"Time": date_list,
"Chocolate": np.random.rand(40),
"Strawberry": np.random.rand(40),
"Fake Chocolate": np.random.rand(40),
"Fake Strawberry": np.random.rand(40),
})
df.iloc[3,3] = np.nan
ax1 = df.plot(x = 'Time', y = ["Chocolate","Strawberry"])
ax1 = df.plot(x = 'Time', y = ["Chocolate","Strawberry"])
ax2 = df.plot.scatter(x = 'Time', y = ['Fake Chocolate'], marker = '^', ax = ax1)
ax3 = df.plot.scatter(x = 'Time', y = ['Fake Strawberry'], marker = '*', ax = ax1, color = '#ff7f0e')
plt.xticks(rotation=45);
推荐阅读
- reactjs - 未捕获的语法错误:在 reactjs 中导入 firestorev9 时无法在模块外使用 import 语句
- c++ - 指针参数不用于在虚函数中修改(MISRA)
- c# - C# 将图像从 .pak 存档加载到图片框
- r - 有什么办法可以加快这个循环?
- symfony - 是否可以为特定用户角色生成 OpenAPI 文档?
- swagger - Smallrye / Quarkus openapi 微配置文件会修剪包含点“。”的@ExampleObject#value。
- python - Python完美数
- linux - 使用 bc(Unix 基本计算器)时如何使用括号?
- angular - 当我们使用 Nginx 部署 Angular 应用程序时,究竟会发生什么?
- javascript - 尝试更新用户收到错误无法发布 /update-user