使用MatPlotLib绘制梯度面积图

ndasle7k  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(138)

我已经编写了以下脚本,使面积图与梯度埃克森和沃尔玛。
该图有梯度,从左到右,而不是我想梯度是最黑暗的最高关闭值,并在每个酒吧底部最轻。
CSV数据文件位于URL..(1)http://salilgangal.com/info/XOM.csv ..(2)http://salilgangal.com/info/WMT.csv

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import pandas as pd

def create_area_plot(xx, yy, gradient_cmap, filename, title, y_offset):
    fig, ax = plt.subplots()
    
    # Create a closed path from the data
    path_data = np.column_stack((xx, yy))
    path_data = np.vstack([path_data, [xx[-1], y_offset], [xx[0], y_offset]])  # Close the path
    path = Path(path_data)
    patch = PathPatch(path, facecolor='none')
    ax.add_patch(patch)

    # Calculate the gradient color values
    color_values = np.linspace(0, 1, len(xx))
    
    # Create a smooth gradient-filled area chart
    for i in range(len(xx) - 1):
        ax.fill_between(xx[i:i+2], [yy[i], yy[i]], [y_offset, y_offset], color=gradient_cmap(color_values[i]))

    # Customize the plot
    ax.set_xlabel('Date')
    ax.set_ylabel('Close')
    ax.set_title(title)
    
    # Format the X-axis labels as 'mm/dd/yyyy'
    ax.set_xticks(xx[::len(xx)//10])  # Adjust the number of ticks for better readability
    ax.set_xticklabels([x.strftime('%m/%d/%Y') for x in pd.to_datetime(xom_dates[::len(xx)//10])], rotation=45, ha="right")
    
    plt.savefig(filename)
    plt.show()
    plt.close()

xom_data = pd.read_csv('XOM.csv')
wmt_data = pd.read_csv('WMT.csv')

xom_data['Date'] = pd.to_datetime(xom_data['Date'])
wmt_data['Date'] = pd.to_datetime(wmt_data['Date'])

xom_dates = xom_data['Date'].dt.strftime('%Y-%m-%d')
wmt_dates = wmt_data['Date'].dt.strftime('%Y-%m-%d')
xom_close_prices = xom_data['Close']
wmt_close_prices = wmt_data['Close']

xx = np.arange(0, xom_dates.size, 1)

yy_xom = xom_close_prices.values
yy_wmt = wmt_close_prices.values

# Define the Y-axis offset as 5% lower than the lowest Close value for each stock
y_offset_xom = min(yy_xom) - 0.05 * (max(yy_xom) - min(yy_xom))
y_offset_wmt = min(yy_wmt) - 0.05 * (max(yy_wmt) - min(yy_wmt))

create_area_plot(xx, yy_xom, plt.cm.Blues, "xom_area_chart.png", "XOM Stock Prices", y_offset_xom)
create_area_plot(xx, yy_wmt, plt.cm.Reds, "wmt_area_chart.png", "WMT Stock Prices", y_offset_wmt)

详细信息在代码中给出

xv8emn3q

xv8emn3q1#

据我所知,这需要一个“手滚”的解决方案,没有干净或整洁的方式。
1.用你的数据创建一个数组(即直方图的外观)并使用imshow。在那里你可以指定颜色值作为数组的值。
1.使用matplotlib.patches.Rectangle创建不同颜色的矩形,并将它们垂直堆叠以重新创建图像。
1.使用多色线(colorline),其中每一条线都是一个条形(您仍然需要计算条形末端的颜色):https://nbviewer.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
这些可能性都不是很大,但他们会做的工作(不知何故)。

相关问题