Here's the updated code with different colors for each group and x-axis labels removed:
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 ---
# You can skip this part if you already have your time-rna.tsv 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 to ensure proper grouping on the chart ---
df.sort_values(by=['Time(min)', 'RNAPol(ul)'], inplace=True)
# --- 4. Create the bar chart with different colors for each group ---
fig, ax = plt.subplots(figsize=(15, 7))
# Define a color palette - you can customize these colors
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3',
'#54a0ff', '#48dbfb', '#1dd1a1', '#feca57', '#ff6b9d', '#c44569']
# Get numerical positions for each bar
x_positions = np.arange(len(df))
# --- 5. Plot bars with different colors for each group ---
group_start_x = 0
group_separators = []
color_index = 0
# Iterate through groups to assign colors and add labels
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
# Get positions for this group
group_positions = x_positions[group_start_x:group_start_x + group_size]
# Plot bars for this group with the same color
ax.bar(group_positions, group_df['RNA(ng/ul)'],
color=colors[color_index % len(colors)],
edgecolor='black', linewidth=0.5)
# Calculate the center position of the group on the x-axis
center_x = (group_start_x + group_end_x) / 2
# Create the group label string
group_label = f"Time: {time}min\nRNAPol: {rnapol}ul"
# Add the label below the x-axis, centered on the group
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="wheat", ec="b", lw=0.5, alpha=0.8))
# Add a vertical line to separate groups (except for the last group)
if group_end_x < len(df) - 1:
group_separators.append(group_end_x + 0.5)
group_start_x += group_size
color_index += 1
# Plot all group separators at once
for sep_pos in group_separators:
ax.axvline(x=sep_pos, color='gray', linestyle='--', linewidth=1)
# --- 6. Remove x-axis labels ---
ax.set_xticks([]) # This removes all x-axis tick marks and labels
# Set plot labels and title
ax.set_ylabel('RNA (ng/ul)')
ax.set_title('RNA Production by Experiment Type')
ax.grid(axis='y', linestyle='--', alpha=0.7)
# Ensure Y-axis starts from 0
ax.set_ylim(bottom=0)
# --- 7. Adjust layout and show plot ---
plt.tight_layout()
plt.subplots_adjust(bottom=0.25)
plt.show()
Key changes made:
-
Color Palette: Added a list of distinct colors that will be assigned to each group:
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3',
'#54a0ff', '#48dbfb', '#1dd1a1', '#feca57', '#ff6b9d', '#c44569']
These are hex color codes that provide good visual distinction between groups.
-
Group-wise Plotting: Instead of plotting all bars at once, the code now iterates through each group and plots its bars with a specific color:
ax.bar(group_positions, group_df['RNA(ng/ul)'],
color=colors[color_index % len(colors)],
edgecolor='black', linewidth=0.5)
The color_index % len(colors) ensures that if you have more groups than colors, it will cycle back to the beginning of the color list.
-
Removed X-axis Labels: Added ax.set_xticks([]) which removes all tick marks and labels from the x-axis, so you won't see the experiment names like "180-1", "180-2", etc.
The result is a cleaner chart where:
- Each group (combination of Time and RNAPol) has its own distinct color
- No individual experiment names clutter the x-axis
- The group information (Time and RNAPol values) is clearly displayed below each group
- Vertical dashed lines separate the groups for clarity