-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen5.py
More file actions
205 lines (182 loc) · 5.88 KB
/
gen5.py
File metadata and controls
205 lines (182 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import sys
import pandas as pd
import urllib.parse
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Usage Check
if len(sys.argv) < 3:
print("Usage: python generate_plot.py <input_csv> <output_html>")
sys.exit(1)
input_csv = sys.argv[1]
output_html = sys.argv[2]
# 1. Load and Process Data
try:
df = pd.read_csv(input_csv)
# Cleanup typical Excel-to-CSV artifacts
cols_to_drop = [c for c in df.columns if 'Unnamed' in c]
if cols_to_drop:
df = df.drop(columns=cols_to_drop)
#df = df.sort_values(by='citations', ascending=False)
# Create Short Title for Axis
df['Title_Short'] = df['Title'].apply(lambda x: str(x)[:40] + '...' if len(str(x)) > 40 else str(x))
# Generate Google Scholar URLs
df['Scholar_URL'] = df['Title'].apply(lambda x: f"https://scholar.google.com/scholar?q={urllib.parse.quote(str(x))}")
except Exception as e:
print(f"Error processing data: {e}")
sys.exit(1)
# 2. Create Figure
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add Bar Trace (Citations)
fig.add_trace(
go.Bar(
x=df['Title_Short'],
y=df['citations'],
name="Citations",
marker_color='rgb(55, 83, 109)',
# Store full data in customdata for hover and click events
customdata=df[['Title', '% of total', 'Cummulative', 'Scholar_URL']],
hovertemplate="<b>%{customdata[0]}</b><br>" +
"Citations: %{y}<br>" +
"% of Total: %{customdata[1]:.2%}<br>" +
"<i>Click bar to search</i><extra></extra>"
),
secondary_y=False,
)
# Add Line Trace (Cumulative Percentage)
fig.add_trace(
go.Scatter(
x=df['Title_Short'],
y=df['Cummulative'],
name="Cumulative %",
marker_color='rgb(26, 118, 255)',
mode='lines+markers',
customdata=df[['Title']],
hovertemplate="<b>%{customdata[0]}</b><br>Cumulative: %{y:.2%}<extra></extra>"
),
secondary_y=True,
)
# 3. Define Buttons for Log/Linear Toggle (Chart Control)
updatemenus = [
dict(
type="buttons",
direction="left",
buttons=list([
dict(
args=[{"yaxis.type": "linear"}],
label="Linear Scale",
method="relayout"
),
dict(
args=[{"yaxis.type": "log"}],
label="Log Scale",
method="relayout"
)
]),
pad={"r": 10, "t": 10},
showactive=True,
x=0.0,
xanchor="left",
y=1.15,
yanchor="top"
),
]
# 4. Layout Configuration
fig.update_layout(
title_text="Citation Counts and Cumulative Distribution",
xaxis_title="Paper Title",
hovermode="closest",
legend=dict(x=0.7, y=0.9),
margin=dict(b=150, t=120),
updatemenus=updatemenus,
height=700 # Explicitly set height to prevent squishing
)
fig.update_xaxes(tickangle=45)
fig.update_yaxes(title_text="<b>Citation Count</b>", secondary_y=False, type="log")
fig.update_yaxes(title_text="<b>Cumulative %</b>", secondary_y=True, tickformat='.0%', showgrid=False)
# 5. Generate HTML Components
plot_html = fig.to_html(full_html=False, include_plotlyjs='cdn')
# Generate the List HTML
list_items = []
for index, row in df.iterrows():
item = f'<li><a href="{row["Scholar_URL"]}" target="_blank" style="text-decoration: none; color: #3366cc;">{row["Title"]}</a> - <b>{row["citations"]}</b> citations</li>'
list_items.append(item)
list_html = f"""
<div id="paper-list-container" style="display: block; font-family: Arial, sans-serif; margin: 20px;">
<h3>Paper List (Sorted by Citations)</h3>
<ul>
{''.join(list_items)}
</ul>
</div>
"""
# Toggle Button HTML
toggle_button_html = """
<div style="margin: 20px; font-family: Arial, sans-serif;">
<button id="toggle-btn" onclick="toggleList()" style="padding: 10px 20px; font-size: 16px; cursor: pointer;">Hide Paper List</button>
</div>
"""
# Custom JavaScript
custom_js = """
<script>
// 1. Toggle List Function
function toggleList() {
var x = document.getElementById("paper-list-container");
var btn = document.getElementById("toggle-btn");
if (x.style.display === "none") {
x.style.display = "block";
btn.innerText = "Hide Paper List";
} else {
x.style.display = "none";
btn.innerText = "Show Paper List";
}
}
// 2. Plotly Bar Click Interaction
// We use an interval to ensure the plot div is fully loaded before attaching the event
var checkPlot = setInterval(function(){
var plotElement = document.getElementsByClassName('plotly-graph-div')[0];
if (plotElement) {
clearInterval(checkPlot);
plotElement.on('plotly_click', function(data){
if(data.points.length > 0){
var point = data.points[0];
var url = null;
if(point.data.type === 'bar') {
url = point.customdata[3];
}
if(url && url.startsWith('http')){
window.open(url, '_blank');
}
}
});
}
}, 500);
</script>
"""
# 6. Assemble Final HTML
full_html_content = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Citation Visualization</title>
<style>
body {{ margin: 0; padding: 0; font-family: Arial, sans-serif; }}
</style>
</head>
<body>
<div style="width: 95%; margin: auto; min-height: 700px;">
{plot_html}
</div>
<hr>
{toggle_button_html}
{list_html}
{custom_js}
</body>
</html>
"""
# 7. Write to file
try:
with open(output_html, 'w', encoding='utf-8') as f:
f.write(full_html_content)
print(f"Successfully created: {output_html}")
except Exception as e:
print(f"Error writing file: {e}")