You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R+Plotly+Shiny中绘制双X轴图表:Flow与Depth关联可视化

Got it, let's break down how to create this dual-axis plot where Depth sits on the Y-axis, with Flow In and Flow Out as separate X-axes. I'll show you two common approaches using Python's most popular plotting libraries—Matplotlib (for full customization) and Seaborn (for quick, polished visuals).

Using Matplotlib (Full Control & Flexibility)

This method gives you precise control over every element of your plot, which is great if you need to tweak styling for reports or publications.

Step 1: Import Required Libraries

First, grab the tools we need:

import matplotlib.pyplot as plt
import pandas as pd

Step 2: Load or Prepare Your Data

If your data is in a CSV file, use pd.read_csv('your_file_path.csv') to load it. For this example, I'll use sample data that mirrors your structure:

# Replace this with your actual dataset
data = pd.DataFrame({
    'Depth': [10, 20, 30, 40, 50],  # Example depth values
    'Flow In': [5, 12, 18, 22, 25],
    'Flow Out': [3, 9, 15, 20, 23]
})

Step 3: Build the Dual X-Axis Plot

We'll create one axis for Flow In, then add a second X-axis (sharing the same Y-axis for Depth) for Flow Out:

# Initialize figure and first axis (Flow In vs Depth)
fig, ax1 = plt.subplots(figsize=(10, 6))

# Plot Flow In on the first X-axis
color = 'tab:blue'
ax1.set_xlabel('Flow In', color=color)
ax1.plot(data['Flow In'], data['Depth'], marker='o', color=color, label='Flow In')
ax1.tick_params(axis='x', labelcolor=color)
ax1.set_ylabel('Depth')
ax1.invert_yaxis()  # Optional: flip Y-axis so deeper depths are at the bottom (standard in hydrology)

# Add second X-axis for Flow Out (shares the Y-axis with ax1)
ax2 = ax1.twiny()

color = 'tab:orange'
ax2.set_xlabel('Flow Out', color=color)
ax2.plot(data['Flow Out'], data['Depth'], marker='s', color=color, label='Flow Out')
ax2.tick_params(axis='x', labelcolor=color)

# Add legend and title for clarity
fig.legend(loc='upper right', bbox_to_anchor=(1.15, 1))
plt.title('Flow In & Flow Out vs Depth')
plt.tight_layout()  # Adjust spacing to prevent label cutoff
plt.show()

Alternative: Using Seaborn (Quick, Polished Visuals)

If you prefer a cleaner, more modern look with less boilerplate code, Seaborn is a great choice—it builds on Matplotlib, so you can still customize things if needed.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Load your data (same as before)
data = pd.DataFrame({
    'Depth': [10, 20, 30, 40, 50],
    'Flow In': [5, 12, 18, 22, 25],
    'Flow Out': [3, 9, 15, 20, 23]
})

# Set a clean style
sns.set_style("whitegrid")
fig, ax1 = plt.subplots(figsize=(10, 6))

# Plot Flow In
sns.lineplot(x='Flow In', y='Depth', data=data, marker='o', color='tab:blue', ax=ax1, label='Flow In')
ax1.set_xlabel('Flow In', color='tab:blue')
ax1.tick_params(axis='x', colors='tab:blue')
ax1.invert_yaxis()

# Add second axis for Flow Out
ax2 = ax1.twiny()
sns.lineplot(x='Flow Out', y='Depth', data=data, marker='s', color='tab:orange', ax=ax2, label='Flow Out')
ax2.set_xlabel('Flow Out', color='tab:orange')
ax2.tick_params(axis='x', colors='tab:orange')

# Final touches
fig.legend(loc='upper right', bbox_to_anchor=(1.15, 1))
plt.title('Flow In & Flow Out vs Depth')
plt.tight_layout()
plt.show()

Quick Notes

  • If you want scatter plots instead of line plots, replace plot() with scatter() (Matplotlib) or use sns.scatterplot() (Seaborn).
  • The invert_yaxis() line is optional but recommended if your Depth values increase downward (common in fields like hydrology or oceanography).

内容的提问来源于stack exchange,提问作者Tappy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:05:53