Certainly! Let's enhance the previous bar chart by:
✅ Coloring each group differently
❌ Removing the x-axis labels (i.e., the Name labels)
🔁 Keeping the group labels (Time & RNAPol) and separators below the bars
Here’s the updated Python code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from io import StringIO
# --- 1. Create a dummy file for demonstration if time-rna.tsv doesn't exist ---
# Skip this if you already have the file
file_content = """Name Time(min) RNAPol(ul) RNA(ng/ul)
180-1 180 1 0
180-2 180 1 11.7
180-3 180 1 12.8
0.5-1 180 0.5 7.2
0.5-2 180 0.5 8.34
60-A 60 1 5.1
60-B 60 1 6.0
60-C 60 1 5.5
180-4 180 1 13.0
240-X 240 0.75 9.1
240-Y 240 0.75 9.5
240-Z 240 0.75 8.8
"""
try:
with open('time-rna.tsv', 'x') as f:
f.write(file_content)
print("Created 'time-rna.tsv' with dummy data for demonstration.")
except FileExistsError:
print("'time-rna.tsv' already exists, using existing file.")
# --- End of dummy file creation ---
# --- 2. Load the data ---
try:
df = pd.read_csv('time-rna.tsv', sep='\t')
except FileNotFoundError:
print("Error: 'time-rna.tsv' not found. Please ensure the file is in the same directory.")
print("Exiting program.")
exit()
# --- 3. Sort the data ---
df.sort_values(by=['Time(min)', 'RNAPol(ul)'], inplace=True)
# --- 4. Generate a unique color for each group ---
# We'll map each (Time, RNAPol) combination to a color
unique_groups = df[['Time(min)', 'RNAPol(ul)']].drop_duplicates()
group_colors = plt.cm.tab20(np.linspace(0, 1, len(unique_groups))) # Use a colormap with 20 colors
group_color_map = dict(zip(unique_groups.itertuples(index=False), group_colors))
# Assign a color to each row based on its group
df['color'] = df.apply(lambda row: group_color_map[(row['Time(min)'], row['RNAPol(ul)'])], axis=1)
# --- 5. Create the bar chart ---
fig, ax = plt.subplots(figsize=(15, 7))
# Bar positions
x_positions = np.arange(len(df))
bar_heights = df['RNA(ng/ul)']
# Plot bars with group-specific colors
bars = ax.bar(x_positions, bar_heights, color=df['color'])
# Hide x-axis labels (the Name values)
ax.set_xticks([]) # No ticks
ax.set_xlabel('') # No x-axis label
# Add group labels below bars
group_start_x = 0
group_separators = []
for (time, rnapol), group_df in df.groupby(['Time(min)', 'RNAPol(ul)'], sort=False):
group_size = len(group_df)
group_end_x = group_start_x + group_size - 1
center_x = (group_start_x + group_end_x) / 2
group_label = f"Time: {time}min\nRNAPol: {rnapol}ul"
# Add group label below the bars
ax.text(center_x, -0.25, group_label,
ha='center', va='top', transform=ax.get_xaxis_transform(),
fontsize=9, bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="black", lw=0.5, alpha=0.8))
# Add vertical separator lines between groups
if group_end_x < len(df) - 1:
group_separators.append(group_end_x + 0.5)
group_start_x += group_size
# Draw separators
for sep_pos in group_separators:
ax.axvline(x=sep_pos, color='gray', linestyle='--', linewidth=1)
# Add vertical axis label and title
ax.set_ylabel('RNA (ng/ul)')
ax.set_title('RNA Production by Experiment Type')
ax.grid(axis='y', linestyle='--', alpha=0.7)
# Set y-axis to start at 0
ax.set_ylim(bottom=0)
# Adjust layout
plt.tight_layout()
plt.subplots_adjust(bottom=0.25) # Extra space for group labels
# Show the plot
plt.show()
✅ What’s New:
| Feature | Description |
|---|
| 🎨 Unique Colors | Each group (defined by Time and RNAPol) is colored distinctly using tab20 colormap. |
| ❌ No X-axis Labels | ax.set_xticks([]) and ax.set_xlabel('') remove the Name labels from the x-axis. |
| 📦 Group Labels | Still shown below the bars for clarity. |
| 🧱 Group Separators | Vertical dashed lines improve visual separation between groups. |
🖼️ Output:
You’ll get a clean, visually organized bar chart showing RNA levels, grouped by experiment conditions, with distinct colors per group and no cluttered x-axis labels.
Let me know if you want to export this as an image (e.g., PNG or PDF), or need tooltips or interactive features!